函数
- 可以有多个返回值
- 所有参数都是值传递: slice, map, channel 会有传引用的错觉
- 函数可以作为变量量的值
- 函数可以作为参数和返回值
函数:可变参数及 defer
可变参数
func sum(ops ...int) int {
s := 0
for _, op := range ops {
s += op
}
return s
}
defer 函数
func TestDefer(t *testing.T) {
defer func() {
t.Log("Clear resources")
}()
t.Log("Started")
panic("Fatal error”) //defer仍会执行
}
demo
// 返回俩个随机数
func returnMultiValues() (int, int) {
return rand.Intn(15), rand.Intn(30)
}
// 计算函数操作的时长
func timeSpent(inner func(op int) int) func(op int) int {
return func(n int) int {
start := time.Now()
ret := inner(n)
fmt.Println("time spent:", time.Since(start).Seconds())
return ret
}
}
func slowFun(op int) int {
time.Sleep(time.Second * 1)
return op
}
func TestFn(t *testing.T) {
a, b := returnMultiValues()
t.Log(a, b)
timeSF := timeSpent(slowFun)
t.Log(timeSF(10))
}
func Sum(ops ...int) int {
ret := 0
for _, op := range ops {
ret += op
}
return ret
}
func TestVarParam(t *testing.T) {
t.Log(Sum(1, 2, 3, 4))
t.Log(Sum(1, 2, 3, 4, 5))
}
func Clear() {
fmt.Println("Clear resources.")
}
func TestDefer(t *testing.T) {
defer Clear()
fmt.Println("Start")
//panic("err")
}
demo1
func TestFn(t *testing.T) {
a, b := returnMultiValues()
t.Log(a, b)
timeSF := timeSpent(slowFun)
t.Log(timeSF(10))
}
result1:
=== RUN TestFn
fun_test.go:32: 11 27
time spent: 1.0093736
fun_test.go:34: 10
--- PASS: TestFn (1.01s)
PASS
demo2
func TestVarParam(t *testing.T) {
t.Log(Sum(1, 2, 3, 4))
t.Log(Sum(1, 2, 3, 4, 5))
}
result:
=== RUN TestVarParam
fun_test.go:47: 10
fun_test.go:48: 15
--- PASS: TestVarParam (0.00s)
PASS
demo3
func TestDefer(t *testing.T) {
defer Clear()
fmt.Println("Start")
//panic("err")
}
result:
=== RUN TestDefer
Start
Clear resources.
--- PASS: TestDefer (0.00s)
PASS