我对 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{} 是一种类型。它由两部分组成:底层类型和底层值。大小无关紧要。成本是每次转换或转换为它时,您都会产生成本。大小影响的一件事是从结构复制到接口(interface)底层值期间的值。但是这个成本类似于您分配给结构或复制到结构时获得的成本。接口(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/

10-11 22:12
查看更多