英文:
Casting Interface{} to specific Type
问题
我正在尝试创建一个通用函数来保存到数据存储。以下两个示例中的第二个可以工作,但第一个会给我一个"datastore: invalid entity type"错误。
我对Go语言的了解非常有限,但正在努力减少我的无知。是否有一种方法可以将第一个示例中的对象转换为一个字符串类型的名称所表示的类型?例如,一种反射的方式。我尝试使用reflect.ValueOf,但没有成功。
提前感谢您的帮助。
示例1:
func save(kind string, c.appengine.Context, object interface{}) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)
示例2:
func save(kind string, c.appengine.Context, object MyType) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)
英文:
I'm trying to make a generic function for saving to the datastore. The second of the following two examples works, but the first gives me a "datastore: invalid entity type" error.
I'm vastly ignorant about Go at the moment, but attempting to decrease my ignorance. Is there some way to cast object in the first example into a type the name of which is held in a string. Eg some kind of reflection. I tried reflect.ValueOf, but failed with it.
Thanks in advance
Example 1:
func save(kind string, c.appengine.Context, object interface{}) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)
Example2:
func save(kind string, c.appengine.Context, object MyType) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, &object)
}
save("MyType", c, someMyTypeObject)
答案1
得分: 1
datastore.Put
方法的第三个参数需要一个结构体指针,但你传递的是一个指向接口的指针,在这种情况下是无效的。
为了解决这个问题,你需要在调用save
时传递一个指针,并将其直接传递给datastore.Put
。
func save(kind string, c appengine.Context, object interface{}) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, object)
}
save("MyType", c, &someMyTypeObject)
你可以将这个过程看作是通过save
将someMyTypeObject
传递给datastore.Put
,而save
并不知道它是什么类型的对象。
英文:
datastore.Put
takes a struct pointer as its 3rd parameter, but you are passing a pointer to an interface which is invalid in this case.
To get around this, you need to pass a pointer when calling save
and pass that as is to datastore.Put
.
func save(kind string, c appengine.Context, object interface{}) {
k := datastore.NewKey(c, kind, "some_key", 0, nil)
_, err := datastore.Put(c, k, object)
}
save("MyType", c, &someMyTypeObject)
You can think of this as passing someMyTypeObject
to datastore.Put
via save
without save
knowing what it is.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论