函数
- 可以有多个返回值
- 所有参数都是值传递,slice,map,channel会有传引用的错觉
- 函数可以作为变量的值
- 函数可以作为参数和返回值
package func_test
import "testing"
import "fmt"
import "time"
import "math/rand"
func returnMultiValues()(int,int) {
return rand.Intn(10),rand.Intn(20)
}
func TestMultiValues(t *testing.T) {
a,b := returnMultiValues()
t.Log(a,b)
c,_ := returnMultiValues()
t.Log(c)
tsSF := timeSpent(slowFunc)
t.Log(tsSF(10))
}
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 slowFunc(op int) int {
time.Sleep(time.Second * 1)
return op
}
可变长参数
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))
}
延迟执行defer函数
unc Clear() {
fmt.Println("clear resources!")
}
func TestDefer(t *testing.T) {
defer Clear()
fmt.Println("Start")
panic("err")
}
网友评论