结构体和方法
基础
仅支持封装,不支持继承和多态,所以没有class只有struct
访问符号为. ,没有->1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25type NAME struct{}
type point struct {
x, y int
}
p :=point{x:1}//如果只想赋值部分可通过指定名称来赋值
p1 := point{1, 2}
p2 := point{}
var p3 point
fmt.Println(p)//{1,0}
fmt.Println(p1)//{1,2}
fmt.Println(p1.x)//1
fmt.Println(p2)//{0,0} 不给初值 默认是zeroValue
fmt.Println(p3)//{0,0}
//或者可以采用new的方式
p4 := new(point)
fmt.Println(p4)//&{0,0}
ap := []point{
{},
{1,2},
{},
}
fmt.Println(ap)//[{0 0} {1 2} {0 0}]没有构造函数,所以可以采用工厂函数的方式
1
2
3
4
5
6
7
8
9
10func createPoint(x, y int) point {
return point{x,y}
}
func createPointP(x, y int) *point {
return &point{x,y}//c/c++中这里会出错,因为是一个局部变量的地址,但是go不会,编译时由编译器决定创建在栈上还是堆上
}
fmt.Println(createPoint(2,3))//{2 3}
fmt.Println(createPointP(3,4))//&{3 4}example 二叉树
1
2
3
4type node struct {
value int
left,right *node
}
func main() {
root := node{value:3}
root.left = &node{value:5}
root.right = new(node)
fmt.Println(root)//{3 0xc42000a080 0xc42000a0a0}
}
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
42
43
44
45
46
2. 方法
go的方法并不是定义在struct内部
其实与函数只是语法上的区别,将参数提到了前面
值/指针接受者 均可以接受值/指针
```go
func (NAME type) funcname(args) returnValue{}
//因为go都是值传递,所以如果要改变本身需要传递指针
func (NAME *type) funcname(arts) returnValue{}
func (self node) print() {
self.value=777
fmt.Println(self.value)
}
root := node{value:3}
root.print()
fmt.Println(root)
pRoot := &root
PRoot.print()
fmt.Println(root)
/*
777
{3 <nil> <nil>}
777
{3 <nil> <nil>}
*/
func (self *node) printC(v int) {
self.value=v
fmt.Println(self.value)
}
root.printC()//不管是指针还是值,都直接.即可,go会自动处理传递地址
fmt.Println(root)
pRoot := &root
pRoot.printC(666)
fmt.Println(root)
/*
777
{777 <nil> <nil>}
666
{666 <nil> <nil>}
*/
nil指针也能调用方法,所以最好判断一下
1 | var p *node |
example 二叉树 遍历
1 | func (self *node) traverse() { |