我了解到不允许将 slice 或映射嵌入到 Go 结构中。但我发现了两种解决方法:
var mySlice []int
type myStruct struct {
mySlice
}
type myStruct struct {
mySlice []int
}
我的第一个问题是,谁能解释为什么我们不能直接将 slice 和映射嵌入到结构中?
第二个问题:使用第二种解决方法,是否会对性能产生负面影响?
第三个问题:为什么第一个和第二个解决方法有效?
最佳答案
A field declared with a type but no explicit field name is called an embedded field. An embedded field must be specified as a type name
T
or as a pointer to a non-interface type name*T
, andT
itself may not be a pointer type. The unqualified type name acts as the field name.
你不能嵌入像
map[int]string
这样的类型,这是一个匿名类型。 Spec 需要类型名称。即使您可以嵌入它,它也包含括号,这会使它失去作为标识符的资格,并且再次,规范说不合格的类型名称充当字段名称。只需为其创建一个新类型,然后您就可以嵌入:
type mymap map[int]string
type s struct {
mymap
}
在结构中嵌入类型时,会省略字段名称。在您的第二次尝试中:
type myStruct struct {
mySlice []int
}
您没有省略字段名称(它是
mySlice
),所以这不是嵌入,它是一个常规的命名字段。
关于go - 为什么我们不能将 slice 或映射嵌入到 Go 结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61110680/