使用这段代码示例 ( playground ):
package main
import (
"fmt"
)
type Foo struct {
Name string
}
var data = make(map[string]interface{})
func main() {
data["foo"] = &Foo{"John"}
foo := data["foo"].(*Foo)
fmt.Println(foo.Name)
}
当我向 data
添加一些内容时,该类型会变成一个 interface{}
,因此当我稍后检索该值时,我必须将原始类型断言回到它上面.例如,有没有办法为 data
定义一个 getter 函数,它会自动断言类型?
最佳答案
不是真的,除非你转向 reflect
并尝试以这种方式获取接口(interface)的类型。
但惯用(且更快)的方式仍然是 type assertion (必须在运行时检查的“类型转换”,因为 data
仅包含 interface{}
值)。
如果数据引用特定接口(interface)(而不是通用的interface{}
接口(interface)),就像我 mentioned here ,那么您可以使用直接在其上定义的 Name()
方法。
关于struct - Go 中的自动类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25977731/