Skip to content

Commit 0052457

Browse files
committed
20190511
1 parent c0966a3 commit 0052457

File tree

4 files changed

+102
-0
lines changed

4 files changed

+102
-0
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.

8.函数Function.md

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
## 函数 Function
2+
-Go 函数**不支持** 嵌套,重载 和 默认函数
3+
-但支持一下特性:
4+
    无需声明原型,不定长度变参,多返回值,命名返回值参数,匿名函数,闭包
5+
-定义函数使用关键字 `func` ,且左大括号不能另起一行
6+
-函数也可以作为一种类型使用
7+
8+
//基本结构
9+
func A(a int, b int, c string) {
10+
//...
11+
}
12+
13+
//自定义返回值
14+
func A(a int, b int, c string) (int, int) {
15+
//...
16+
}
17+
18+
//不定长变参,传进来的数据插入a这个slice
19+
func A(a ...int) {
20+
fmt.Println(a)
21+
}
22+
//不定长变参只能写在最后
23+
func A(b string, a ...int) {
24+
fmt.Println(a)
25+
}
26+
函数作为类型使用
27+
28+
func main() {
29+
a := A
30+
a()
31+
}
32+
func A() {
33+
fmt.Println("Func A")
34+
}
35+
36+
匿名函数
37+
38+
func main() {
39+
a := func() {
40+
fmt.Println("Func A")
41+
}
42+
a()
43+
}
44+
45+
闭包
46+
47+
func main() {
48+
f := closure(10)
49+
// 11
50+
fmt.Println(f(1))
51+
}
52+
func closure(x int) func(int) int {
53+
return func(y int) int{
54+
return x + y
55+
}
56+
}
57+
58+
## 延迟调用函数 defer
59+
-在函数体执行结束后按照调用顺序的**相反顺序**逐个执行
60+
-**即使函数发生严重错误也会执行**
61+
-支持匿名函数的调用
62+
-常用于资源清理,文件关闭,解锁以及记录时间等操作
63+
-通过与匿名函数的配置可在 `return` 后修改函数计算结果
64+
-如果函数体内某个变量作为 `defer` 时匿名函数的参数,则在定义 `defer` 时即已经获得了拷贝,否则则是引用某个变量的地址
65+
66+
-Go 没有异常机制,但有 `panic` / `recover` 模式来处理错误
67+
-`panic` 可以在任何地方引发,但 `recover` 只有在 `defer` 调用的函数中有效
68+
69+
//打印结果为 2 1 0
70+
for i := 0; i < 3; i++ {
71+
defer fmt.Println(i)
72+
}
73+
74+
//调用函数 打印结果为 3 3 3
75+
for i := 0; i < 3; i++ {
76+
defer func () {
77+
fmt.Println(i)
78+
}()
79+
}
80+
81+
捕获异常
82+
83+
func main() {
84+
A()
85+
B()
86+
C()
87+
}
88+
func A() {
89+
fmt.Println("A")
90+
}
91+
func B() {
92+
//捕获
93+
defer func() {
94+
if err := recover(); err != nil {
95+
fmt.Println("Recover in B")
96+
}
97+
}()
98+
panic("B")
99+
}
100+
func C() {
101+
fmt.Println("C")
102+
}

0 commit comments

Comments
 (0)