我对 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)
}
最佳答案
Interface{} 是一种类型。它由两部分组成:基础类型和基础值(value)。大小无所谓。成本是每次转换它或转换它时,您都会产生成本。大小效应的一件事是从结构复制到接口(interface)基础值期间的值(value)。但此成本类似于分配给结构或复制到结构时获得的成本。接口(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
}
关于go - golang 将 struct 转换为 interface{} 时发生了什么?成本是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37808237/