在Go语言中使用反射创建指针切片的方法是:

huangapple go评论79阅读模式
英文:

Create slice of pointers using reflection in Go

问题

我看到了一些关于这个主题的反思的例子,但是我找不到解决这个问题的任何东西。这感觉有点复杂,但另一种选择是大量的重复,所以我想试一试。

我有一个返回函数(处理程序)的函数。包装函数传入一个结构体的实例。我需要内部函数创建一个指向该结构体类型的指针切片:

func createCollectionHandler(app *appSession, record interface{}, name string) func(res http.ResponseWriter, req *http.Request) {
	return func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Content-Type", "application/json")

        // 这一行需要是动态的:
		var result []*Person

		err := meddler.QueryAll(app.MysqlDB, &result, "select * from "+name)
		if err != nil {
			log.Fatal(err)
		}
		json, err := json.MarshalIndent(result, "", " ")
		if err != nil {
			log.Println(err)
		}
		res.Write([]byte(json))
		return
	}
}
英文:

I've seen a few examples of reflection around this topic, but I can't find anything that solves this issue. It feels a little convoluted, but the alternative is a massive amount of repetition so I thought I'd give it a try.

I have a function that returns a function (handler). The wrapping function passes in an instance of a struct. I need the inner function to create a slice of pointers to that struct type:

func createCollectionHandler(app *appSession, record interface{}, name string) func(res http.ResponseWriter, req *http.Request) {
	return func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Content-Type", "application/json")

        // This line needs to be dynamic:
		var result []*Person

		err := meddler.QueryAll(app.MysqlDB, &result, "select * from "+name)
		if err != nil {
			log.Fatal(err)
		}
		json, err := json.MarshalIndent(result, "", " ")
		if err != nil {
			log.Println(err)
		}
		res.Write([]byte(json))
		return
	}
}

答案1

得分: 5

你可以使用反射(reflect)和类型示例来创建一个切片,代码如下:

var t *MyType

typeOfT := reflect.TypeOf(t)
sliceOfT := reflect.SliceOf(typeOfT)

s := reflect.MakeSlice(sliceOfT, 0, 0).Interface()

为了在不知道类型的情况下传递切片的指针,你可以先创建指针,然后设置切片的值:

ptr := reflect.New(sliceOfT)
ptr.Elem().Set(reflect.MakeSlice(sliceOfT, 0, 0))
s := ptr.Interface()

你可以在这里查看示例代码:http://play.golang.org/p/zGSqe45E60

英文:

You can create a slice using reflect and an example of the type like so:

var t *MyType

typeOfT := reflect.TypeOf(t)
sliceOfT := reflect.SliceOf(typeOfT)

s := reflect.MakeSlice(sliceOfT, 0, 0).Interface()

In order to pass a pointer to the slice without knowing the type, you can create the pointer first, then set the slice value:

ptr := reflect.New(sliceOfT)
ptr.Elem().Set(reflect.MakeSlice(sliceOfT, 0, 0))
s := ptr.Interface()

http://play.golang.org/p/zGSqe45E60

huangapple
  • 本文由 发表于 2015年10月28日 00:31:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33373443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定