英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论