type Person struct {
ID int `json:"id"`
}
type PersonInfo []Person
type PersonInfo2 [] struct {
ID int `json:"id"`
}
Run Code Online (Sandbox Code Playgroud)
PersonInfo和PersonInfo2之间是否有区别?
主要区别在于如何在PersonInfo/PersonInfo2初始化之外初始化Person对象.由于PersonInfo2是匿名结构类型的数组,因此在PersonInfo2初始化之外我们对此类型一无所知.
所以他们都可以像这样初始化:
m := PersonInfo{{1}, {2}}
n := PersonInfo2{{1},{2}}
Run Code Online (Sandbox Code Playgroud)
但是,如果我们想要附加匿名结构类型的元素,我们必须指定完整类型:
append(n, struct { ID int `json:"id"` }{3})
Run Code Online (Sandbox Code Playgroud)
如果我们打印出来,我们可以看到它们看起来是一样的:
fmt.Printf("%+v\n%+v", m, n)
输出:
[{ID:1} {ID:2}]
[{ID:1} {ID:2}]
Run Code Online (Sandbox Code Playgroud)
但是它们不会非常相等,因为PersonInfo是Person类型的数组,而PersonInfo2是一个匿名结构类型的数组.所以以下内容:
if !reflect.DeepEqual(m,n) {
print("Not Equal")
}
Run Code Online (Sandbox Code Playgroud)
将打印"不等于".
这是一个自己看的链接.
当附加到PersonInfo2时,我们必须为我们想要追加的每个值重复匿名结构类型,最好将PersonInfo用作Person类型的数组.