英文:
datastore: invalid entity type on get
问题
嘿,我正在尝试通过传递一个id来获取一个实体,但是看起来我得到了一个空指针。我尝试了几种初始化实体的方式,但结果都是一样的。
我尽量按照这个例子创建我的服务器to-do。
我在这里漏掉了什么?
type UserManager struct {
users []*Users
user *Users
}
func NewUserManager() *UserManager {
return &UserManager{}
}
func (userManager *UserManager) putUser(c appengine.Context, u *Users) (usreRes *Users, err error) {
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "users", nil), u)
if err != nil {
return nil, err
}
c.Debugf("file key inserted :%#v", key)
return u, nil
}
func (userManager *UserManager) getUserById(userKey string, c appengine.Context) (usreRes *Users, err error) {
entity_id_int, err := strconv.ParseInt(userKey, 10, 64)
if err != nil {
return userManager.user, err
}
k := datastore.NewKey(c, "users", "", entity_id_int, nil)
userRes := new(Users)
err = datastore.Get(c, k, &userRes)
if err != nil {
return userManager.user, err
}
return userRes, nil
}
英文:
Hey im trying to get an entity by passing an id ,
But it`s look like im getting a nill pointer
I tried to initialize the entity in couple of ways but the result is the same.
I'm trying to create my server as much as i can like this example
to-do
what am im missing here ?
type UserManager struct {
users []*Users
user *Users
}
func NewUserManager() *UserManager {
return &UserManager{}
}
func (userManager *UserManager) putUser(c appengine.Context, u *Users) (usreRes *Users, err error) {
key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "users", nil), u)
if err != nil {
return nil, err
}
c.Debugf("file key inserted :%#v", key)
return u, nil
}
func (userManager *UserManager) getUserById(userKey string, c appengine.Context) (usreRes *Users, err error) {
entity_id_int, err := strconv.ParseInt(userKey, 10, 64)
if err != nil {
return userManager.user, err
}
k := datastore.NewKey(c, "users", "", entity_id_int, nil)
userRes := new(Users)
err = datastore.Get(c, k, &userRes)
//err = datastore.Get(c, k, &userManager.user)
if err != nil {
return userManager.user, err
}
//return userManager.user,nil
return userRes, nil
}
答案1
得分: 2
这是因为datastore.Get(c, k, "pointer")
期望作为其第三个参数传递一个指向结构体的指针,而你传递的是一个指向指针的指针**userRes
。
你创建了一个指向结构体的指针userRes := new(Users)
参见
所以你应该这样做:
datastore.Get(c, k, userRes)
不需要使用取地址符号,因为使用new
关键字已经创建了一个指针。
英文:
It's because datastore.Get(c, k, "pointer")
expects a pointer to struct as its third argument, and you are passing a pointer of a pointer **userRes
userRes := new(Users)
There you are creating a pointer to struct see
So you should do:
datastore.Get(c, k, userRes)
Without the ampersand, because with new keyword you are already creating a pointer
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论