Golang:将接口转换回其原始类型

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

Golang: cast interface back to its original type

问题

我无法真正找到这个问题的答案,尽管我查阅了Go的文档和示例。是否可能将接口转换回其原始类型,动态地进行转换?我知道可以像这样做:

var myint int = 5
var myinterface interface{}
myinterface = myint
recovered, _ := myinterface.(int)
fmt.Println(recovered)

但是在这里我知道类型。我想要有一个未知类型(接口)的映射,并通过使用反射将它们转换回来,像这样:

// put/pop writes/read to/from a map[string]interface{}
var myint int = 5
put("key", myint)
pop("key", &myint) // 这也适用于对象或任何其他类型

这样就可以在一个单独的映射中存储任何东西。当调用pop()时,类型将由用户传入(第二个参数是一个接口)。是否可能使用反射来实现这一点?

英文:

I couldn't really find an answer to this, even though I looked up the Go documentation and examples. Is it possible to cast an interface back to its original type, dynamically? I know I can do something like this:

var myint int = 5
var myinterface interface{}
myinterface = myint
recovered, _ := myinterface.(int)
fmt.Println(recovered)

But here I know the type. I would like to have a map of unknown types (interfaces) and cast them back by using reflection, like this:

// put/pop writes/read to/from a map[string]interface{}
var myint int = 5
put("key" myint)
pop("key", &myint) // this should also work for objects or any other type

Like this it would by possible to store anything within a single map. The type will be handed in by the user when calling pop() (second argument is an interface). Is it possible to achive this using reflection?

答案1

得分: 12

你可以在编译时不知道接口的具体类型的情况下断言类型,但你可以通过反射从接口中设置一个值。以下是一个没有错误检查的示例,当任何参数不匹配时会引发 panic:

var m = map[string]interface{}{}

func put(k string, v interface{}) {
    m[k] = v
}

func pop(k string, o interface{}) {
    reflect.ValueOf(o).Elem().Set(reflect.ValueOf(m[k]))
}

链接:https://play.golang.org/p/ORcKhtU_3O

英文:

You can't assert a type from an interface without knowing what that type is at compile time, but you can set a value from an interface via reflection. Here's an example without any error checks, which panics when any parameters don't match:

var m = map[string]interface{}{}

func put(k string, v interface{}) {
    m[k] = v
}

func pop(k string, o interface{}) {
    reflect.ValueOf(o).Elem().Set(reflect.ValueOf(m[k]))
}

https://play.golang.org/p/ORcKhtU_3O

huangapple
  • 本文由 发表于 2016年11月10日 01:03:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/40512323.html
匿名

发表评论

匿名网友

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

确定