函数是一等公民
- 可以有多个返回值
- 所有参数传递都是值传递:slice map channel 会有传引用错觉
- 函数可以作为变量的值
- 函数可以作为参数和返回值
package _func
import (
"fmt"
"math/rand"
"testing"
"time"
)
func ReturnMultiValues()(int,int){
return rand.Intn(10),rand.Intn(10)
}
func TimeSpent(inner func(op int) int) func(op int) int {
return func(op int) int{
start := time.Now()
end := inner(op)
fmt.Println("time spent:",time.Since(start).Seconds())
return end
}
}
func slowFunc(op int) int {
time.Sleep(time.Second * 10)
return op
}
func TestFunc(t *testing.T){
a,b :=ReturnMultiValues()
t.Log(a,b)
tssf := TimeSpent(slowFunc)
tssf(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,5,6,7))
t.Log(Sum(1,2,3,4))
}
func TestDefer(t *testing.T){
defer func() {
t.Log("clear")
}()
t.Log(123)
panic(1)
t.Log(1231456)
}