函數(shù)是一等公民:
- 可以有多個返回值
- 所有參數(shù)都是值傳遞:
slice
栖疑、map
、channel
會有傳引用的錯覺 - 函數(shù)可以作為變量的值
- 函數(shù)可以作為參數(shù)和返回值
func returnMultiValues() (int, int) {
// 返回兩個值
return rand.Intn(10), rand.Intn(20)
}
func TestFn(t *testing.T) {
a, b := returnMultiValues()
t.Log(a, b) // 1 7
}
可變參數(shù):
func Sum(ops ...int) int {
ret := 0
for _, op := range ops {
ret += op
}
return ret
}
func TestVarParams(t *testing.T) {
t.Log(Sum(1, 2, 3, 4))
t.Log(Sum(1, 2, 3, 4, 5))
/** 運行結(jié)果
=== RUN TestVarParams
TestVarParams: func_test.go:48: 10
TestVarParams: func_test.go:49: 15
--- PASS: TestVarParams (0.00s)
*/
}
defer:
在最后執(zhí)行完執(zhí)行畜挨,通常我們用于釋放資源及釋放鎖
func TestDefer(t *testing.T) {
defer func() {
t.Log("Clean resources")
}()
t.Log("Started")
// panic 手動觸發(fā)宕機
panic("Fatal error") // defer 仍然會執(zhí)行
/** 運行結(jié)果
=== RUN TestDefer
TestDefer: func_test.go:56: Started
TestDefer: func_test.go:54: Clean resources
--- FAIL: TestDefer (0.00s)
*/
}