go-结构体

概念

结构体是一种聚合的数据类型,有零个或多个任意类型的值聚合成的实体.

声明定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//声明一个结构体类型
type Employee struct {
id int
name string
address string
}

//声明一个结构体类型的变量
var aa Employee
//访问
aa.id

//修改
aa.id = 1

//对成员取地址,通过指针访问
name := &a.name
*name = "edit" + *name

结构体嵌入和匿名成员

嵌入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

/**

// 声明 circle 结构体
type Circle struct {
x,y,radius int
}

// 声明 wheel 结构体
type Wheel struct {
x,y,radius,spokes int
}

**/

//随着几何图形增多,结构体声明有许多重复定义,为了便于维护,将共同的属性独立出来

type Point struct {
x,y int
}

type Circle struct {
Center Point
Radius int
}

type Wheel struct {
Circle Circle
Spokes int
}


func main() {

var w Wheel

w.Circle.Center.y = 8
w.Circle.Center.x = 9
w.Spokes = 20
}

嵌套匿名成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//正常的嵌入结构体访问起来不是很方便,我们可以用go的匿名成员嵌套
//Go语言有一个特性让我们只声明一个成员对应的数据类型而不指名成员的名字;这类成员就叫匿名成员。匿名成员的数据类型必须是命名的类型或指向一个命名的类型的指针

package main

type Point struct {
X,Y int
}

type Circle struct {
Point
Radius int
}

type Wheel struct {
Circle
Spokes int
}

func main() {
var w Wheel
w.X = 8 // 相当于 w.Circle.Point.X = 8
w.Y = 8 // 相当于 w.Circle.Point.Y = 8
w.Radius = 5
w.Spokes = 20

// w = Wheel{8,8,5,20} //结构体字面值没有简短表示匿名成员的方法 此方式不会编译通过
// w = Wheel{X: 8, Y: 8, Radius: 5, Spokes: 20} // compile error: unknown fields

//以下两种赋值是都可以的

w = Wheel{
Circle:Circle{
Point:Point{X:8,Y:8},
Radius:5,
},
Spokes:20,
}

w = Wheel{Circle{Point{8,8},5}, 20}
}