Golang与结构混淆

Blu*_*Joy 3 arrays struct go

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之间是否有区别?

Jac*_*ore 6

主要区别在于如何在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类型的数组.

  • 请注意,切片的初始化不是问题,因为您可以省略`elemnt的类型`并仅使用`{}`,当您想要将新元素附加到切片时会产生痛苦.https://play.golang.org/p/ZQR0zjEFS- (2认同)