go 函数小结

函数

defer

go语言中函数的return不是原子操作,在底层分为两层操作

第一步:返回值赋值

defer

第二步:真正的ret返回

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
47
48
49
50
func f1() int {
x := 5
defer func() {
x++
}()
return x
}

func f2() (x int) {
defer func() {
x++
}()
return 5
}

func f3() (y int) {
x := 5
defer func() {
x++
}()
return x
}
func f4() (x int) {
defer func(x int) {
x++
}(x)
return 5
}
func f5()(x int){
defer func(x int) int{
x++
return x
}(x)
return 5
}

func f6(x int){
defer func(x *int){
(*x)++
}(*x)
return 5
}
func main() {
fmt.Println(f1()) //5
fmt.Println(f2()) //6
fmt.Println(f3()) //5
fmt.Println(f4()) //5
fmt.Println(f5()) //5
fmt.Println(f6()) //6
}

defer 会将值先赋值到函数中

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
func main(){
a := 1
b := 2
defer calc("1", a, calc("10", a, b))
a = 0
defer calc("2", a, calc("20", a, b))
b = 1
}


func calc(index string, a, b int) int{
ret := a +b
fmt.Println(index, a, b, ret)
// 20 0 1
// 2 0 1
// 10 0 1
// 1 0 1
return ret
}

----------------
10 1 2 3
20 0 2 2
2 0 2 2
1 1 3 4

闭包

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

func f11(f func()){
fmt.Println("this is f1")
f()
}

func f22(x, y int) {
fmt.Println("this is f2")
fmt.Println(x + y)
}

func f33(f func(int, int), x, y int) func(){
tmp := func(){
f(x, y)
}
return tmp
}
//实现f1(f2)
func main(){
ret := f33(f22, 100, 200)
f11(ret)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func adder() func(int) int {
var x int
return func(y int) int {
x += y
return x
}
}
func main() {
var f = adder()
fmt.Println(f(10)) //10
fmt.Println(f(20)) //30
fmt.Println(f(30)) //60

f1 := adder()
fmt.Println(f1(40)) //40
fmt.Println(f1(50)) //90
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func calc(base int) (func(int) int, func(int) int) {
add := func(i int) int {
base += i
return base
}

sub := func(i int) int {
base -= i
return base
}
return add, sub
}

func main() {
f1, f2 := calc(10)
fmt.Println(f1(1), f2(2)) //11 9
fmt.Println(f1(3), f2(4)) //12 8
fmt.Println(f1(5), f2(6)) //13 7
}

1、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func calc(index string, a, b int) int {
ret := a + b
fmt.Println(index, a, b, ret)
return ret
}

func main() {
x := 1
y := 2
defer calc("AA", x, calc("A", x, y))
x = 10
defer calc("BB", x, calc("B", x, y))
y = 20
}

上面代码的输出结果是?