struct slice初始化的区别
type Person struct {
ID int `json:"id"`
}
type PersonInfo []Person
type PersonInfo2 []struct {
ID int `json:"id"`
}
PersonInfo
(命名结构的命名切片)和PersonInfo2
(未命名结构的命名切片)之间是否有区别
Go 使用的是structural typing
,这意味着,只要这两种类型具有相同的底层类型,它们就是等价的。
因此,对于您的问题:Person
andstruct{ ID int 'json:"id"'}
是等价的,因为它们具有相同的基础类型,因此,PersonInfo
andPersonInfo2
也是等价的。我使用了 json 标签来简化示例。
person1 := Person{1}
pStruct1 := struct{ID int}{2}
pInfo1 := PersonInfo{
person1,
pStruct1,
}
pInfo2 := PersonInfo2{
person1,
pStruct1,
}
fmt.Printf("%+v\n", pInfo1)
fmt.Printf("%+v", pInfo2);
//outputs
//PersonInfo: [{ID:1} {ID:2}]
//PersonInfo2: [{ID:1} {ID:2}]
代码示例: https: //play.golang.org/p/_wlm_Yfdy2
type PersonInfo
是 的一个对象Person
,而它本身PersonInfo2
就是一个class
(或type
在 Golang 中)。即使它们的数据结构相似。
因此,当您运行 DeepEqual() 来检查相似性时,它会被证明是错误的。
先前评论的示例:
if !reflect.DeepEqual(m,n) {
print("Not Equal")
}
希望这可以帮助。
主要区别在于您必须如何在 PersonInfo/PersonInfo2 初始化之外初始化 Person 对象。由于 PersonInfo2 是一个匿名结构类型的数组,我们在 PersonInfo2 初始化之外对这种类型一无所知。
所以它们都可以像这样初始化:
但是,如果我们想附加一个匿名结构类型的元素,我们必须指定完整类型:
如果我们将这些打印出来,我们可以看到它们看起来是一样的:
fmt.Printf("%+v\n%+v", m, n)
输出:但是它们不会完全相等,因为 PersonInfo 是 Person 类型的数组,而 PersonInfo2 是匿名结构类型的数组。所以如下:
将打印“不等于”。
这是您自己查看的链接。
当追加到 PersonInfo2 时,我们必须为要追加的每个值重复匿名结构类型,最好将 PersonInfo 用作 Person 类型的数组。