3 - 函数

2020-07-02  本文已影响0人  天命_风流
package fn

import (
    "math/rand"
    "testing"
)

func returnMultValues() (int, int){
    return rand.Intn(10), rand.Intn(20)
}

func TestFn(t *testing.T){
    a, b := returnMultValues()
    t.Log(a, b)
}
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 TestTimeSpent(t *testing.T){
    tsSlowFun := timeSpent(slowFun)
    t.Log(tsSlowFun(666))
}
func Sum(ops ...int) int{
    fmt.Println(reflect.TypeOf(ops))  // []int
    sum := 0
    for _, op := range ops{
        sum += op
    }
    return sum
}

func TestVar(t *testing.T){
    t.Log(Sum(1,2,3))
    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("Error")
}

// Start -> Clear resources. -> panic: Error
上一篇下一篇

猜你喜欢

热点阅读