结构切片行为

Slice of structs behaviour

当我们声明一个结构体切片,但将数据类型设置为指向该结构体的指针时,go 会自动将字面量转换为指针吗?

type book struct {
    id int
    name string
}

var books = []*book {
    {1, "Yellow moon"}, // ---> Is this a pointer to book OR just book
}

Does go auto convert composite literals inside a slice to pointers if I declare the slice as a pointer to a struct?

这是指向结构的指针的默认行为

To access the field X of a struct when we have the struct pointer p we could write (*p).X. However, that notation is cumbersome, so the language permits us instead to write just p.X, without the explicit dereference.

https://tour.golang.org/moretypes/4

它将是指向 book 的指针,与 &book{1, "Yellow moon"} 相同,但规范允许省略类型和 & 运算符,因为从类型中可以看出。

var books = []*book {
    {1, "Yellow moon"},  // This is the same as &book{1, "Yellow moon"}
}

Spec: Composite literals:

Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T. Similarly, elements or keys that are addresses of composite literals may elide the &T when the element or key type is *T.

[][]Point{{{0, 1}, {1, 2}}}  // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}

[2]*Point{{1.5, -3.5}, {}}   // same as [2]*Point{&Point{1.5, -3.5}, &Point{}}

可以定义有无类型:

https://play.golang.org/p/CB2MDPDztrc