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条)

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重