dongque5529 2015-02-27 04:39
浏览 74
已采纳

如何在Golang中创建作为参数指定类型的切片? 或如何为Appengine数据存储区getAll提供[]接口{}

I'm trying to create a generator of handlers that works for several kinds of entities. The following code works if the items slice is of a specific type (eg: var items []Person), but I'm having problems generalizing it: specifically "ERROR: Can't get items: datastore: invalid entity type". Any idea of how to declare items so that it have a type valid for GetAll?

func ScaffoldList(entity interface{}, collection string, templ *template.Template) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        c := appengine.NewContext(r)
        T := reflect.TypeOf(entity)
        q := datastore.NewQuery(T.String())
        items := reflect.MakeSlice(reflect.SliceOf(T), 0, 10)
        _, err := q.GetAll(c, &items)
        if err != nil{
            c.Errorf("Can't get items: %v", err)
            http.Error(w, "Can't get items", http.StatusInternalServerError)
            return
        }
        context.Set(r, collection, items)
        ion.RenderTemplate(templ).ServeHTTP(w, r)
    })
}
  • 写回答

2条回答 默认 最新

  • douan7601 2015-02-27 06:08
    关注

    Here's how you get an argument of type *[]Person:

    items := reflect.New(reflect.SliceOf(T))
    _, err := q.GetAll(c, items.Interface())
    

    GetAll will allocate the backing array for the slice. There's no need to preallocate the backing array with make.

    Assuming that the argument to context.Set is a value containing a slice, then you need to dereference the pointer:

    context.Set(r, collection, items.Elem())
    

    If the context does not work with reflect values, then you probably want:

    context.Set(r, collection, items.Elem().Interface())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面