将Interface{}转换为特定类型的方法

huangapple go评论106阅读模式
英文:

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)

你可以将这个过程看作是通过savesomeMyTypeObject传递给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.

huangapple
  • 本文由 发表于 2014年4月3日 05:09:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/22823113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定