1. Definition
A struct is an aggregated data type that combines a named variable of another or more arbitrary types.
2. Member variables
- Access control mechanism
If the member variable name of a struct is larger than the first letter, then the variable is exportable (that is, it can be accessed in other packages).
A struct can contain both exportable and non-exportable member variables
type A struct { Hour int //可导出 minute int //不可导出}
- Limit
A named struct type S cannot define a member variable that has the same struct type S, i.e. an aggregate type cannot contain itself. However, S can be defined as a pointer type of s, that is, *s. As follows:
type B struct { value int //Next B //错误 Next *B //正确}
3. Comparison of structural bodies
- If all member variables of a struct can be compared, the struct can be compared. A comparison of two structures can be used = = or! =.
type C struct { A int B string}c1 := C{A:1, B:"abc"}c2 := C{A:1, B:"abc"}c3 := C{A:2, B:"abc"}fmt.Println(c1.A == c2.A && c1.B == c2.B) //truefmt.Println(c1 == c2) //true 与上等价fmt.Println(c1.A == c3.A && c1.B == c3.B) //falsefmt.Println(c1 == c3) //false 与上等价
2. As with other comparable types, a comparable struct type can be used as the key type for a map.
type C struct { A int B string}mp := make(map[C]int)key := C{A:1, B:"abc"}mp[key] = 9fmt.Println(mp[C{A:1, B:"abc"}]) //9
4. Struct nesting and anonymous members
- Go allows us to define struct members without names, only to specify the type, and this struct member is called an anonymous member. The type of the struct member must be a named type or a pointer to a named type. It is because of this structure nesting function that we can directly access the variables we need instead of specifying a large string of intermediate variables.
type Point struct { X int Y int}type Circle struct { Point}var c Circlec.X = 10 //等价于 c.Point.X = 10c.Y = 10 //等价于 c.Point.Y = 10type Wheel struct { *Point}
- struct literal initialization has no shortcuts and must follow the definition of the shape type.
type Point struct { X int Y int}type Circle struct { Point}var c Circlec = Circle{1,1} //错误c = Circle{Point{1,1}} //正确c = Circle{Point: Point{1,1}} //正确
3. Because an anonymous member has an implicit name, you cannot define two anonymous members of the same type in a struct, or it will cause a conflict. Because the names of anonymous members are determined by their type, their exportable nature is also determined by their type. In the following example, the two anonymous members of point and Circle are exportable, even if the two structures are non-exportable (point and Circle).
type point struct { X int Y int}type circle struct { point}type Wheel struct { circle}var w Wheelw.X = 8 // 等价于 w.circle.point.X = 8, w.X是可导出的,w.circle.point.X是不可导出的