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
| package main
import "fmt"
//定义结构体
type Point struct {
X int
Y int
}
func newPoint(x,y int)*Point{
return &Point{
X: x,
Y: y,
}
}
func main() {
//通过结构体的地址实例化
point :=&Point{
X: 1,
Y: 1,
}
//通过new关键字来实例化结构体
point1 :=new(Point)
point1.X = 1
point1.Y =1
// 用函数封装一下初始化过程
point2 := newPoint(1,1)
fmt.Println(point)
fmt.Println(point1)
fmt.Println(point2)
}
|
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
| package main
import "fmt"
type People struct {
name string
child *[]People
wife *People
}
func main() {
//一个父亲有一个妻子,一个儿子,一个女儿
family := &People{
name: "father",
child: &[]People{
{"boy", nil, nil},
{"girl", nil, nil},
},
wife: &People{
name: "wife",
child: &[]People{
{"boy", nil, nil},
{"girl", nil, nil},
},
wife: nil,
},
}
fmt.Println(family)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| package main
import "fmt"
func main() {
cat :=&struct {
Name string
Color string
}{
"huahua",
"red",
}
fmt.Println(*cat)
}
|
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
| package main
import "fmt"
type Cat struct {
Color string
Name string
}
// 为结构体设置方法,注意这里的对象是*cat是指针类型
func (cat *Cat) setColor(color string){
cat.Color = color
}
//为结构体设置方法,这里是非指针类型,可以达到类似只读的效果
func (cat Cat) setColor1(color string){
cat.Color = color
}
func NewCatByName(name string) *Cat{
return &Cat{
Name: name,
}
}
func main() {
huahua :=NewCatByName("huahua")
huahua.setColor("red")
fmt.Println(huahua) //&{red huahua}
huahua.setColor1("white")
//颜色并没有改变
fmt.Println(huahua) //&{red huahua}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| package main
import "fmt"
//类型内嵌,只定义类型,不定义字段名称
type Data struct {
int
float64
}
func main() {
d := Data{
int: 1,
float64: 1.5,
}
//字段同类型名称相同,可以直接通过类型访问
fmt.Println(d.float64)
fmt.Println(d.int)
}
|
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
| package main
import "fmt"
//能走
type Walk struct {}
func (w *Walk) canWalk(){
fmt.Println("can walk")
}
//能跑
type Run struct {}
func (r *Run)canRun(){
fmt.Println("can run")
}
type Children struct {
Walk
}
type Man struct {
Walk
Run
}
func main() {
children := new(Children)
//这样可以直接访问结构体里的方法
children.canWalk()
man :=&Man{}
man.canRun()
man.canWalk()
}
|