golang学习 函数

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// func
package main

import (
"fmt"
)

func main() {
fmt.Println("Hello World!")

value, nextPos := nextInt(1, 2)

fmt.Println(value, nextPos)

// 延迟执行
for i := 0; i < 5; i = i + 1 {

defer fmt.Println("defer i -> ", i)
}

// 函数作为数值
a := func(a int, b int) int {
return (a + b)
}

fmt.Println(a(6, 7))

fmt.Printf("%Tn", a)

//回调
callback := func(n int, f func(int, int) int) int {

return f(n, n) * f(n, n)
}

fmt.Printf("callback -> %d", callback(2, a))

// panic & recover

pf := func() {

//panic(1)
}

fmt.Println(throwPanic(pf))
}

// 命名返回值
func nextInt(n int, k int) (value, nextPos int) {

value = 0
nextPos = 9

return
}

// 可变参数
func output(args ...int) {

}

// panic & recover
func throwPanic(f func()) (b bool) {

defer func() {

if x := recover(); x != nil {

b = true
}
}()

f()

return
}