Don*_*Liu 4 struct interface go
我对interface{}类型感到困惑,
如何从Person结构构建interface{}对象?
如果结构体很大,转换成本是否昂贵
type Person struct {
name string
age int
}
func test(any interface{}) {
}
func main() {
p := Person{"test", 11}
// how to build an interface{} object from person struct?
// what is the cost? the field need copy?
test(p)
}
Run Code Online (Sandbox Code Playgroud)
Interface{} 是一种类型。它由两部分组成:基础类型和基础值。大小并不重要。成本是指每次转换它或转换成它时,都会产生成本。大小效应的一件事是从结构复制到接口底层值期间的值。但此成本类似于分配给结构或复制到结构时获得的成本。接口的额外成本不受尺寸影响。
您不需要该函数来转换,您可以这样转换:
func main() {
p := Person{"test", 11}
// how to build an interface{} object from person struct?
// what is the cost? the field need copy?
var v interface{}
v = p
}
Run Code Online (Sandbox Code Playgroud)