Go(二)函数

函数是一等公民

与其他主要编程语言的差异

1.可以有多个返回值

2.所有参数都是值传递

       slice、map、channel会有传引用是错觉,如切片背后是数组,是一个数据结构,里面包含了指向对应数组的指针,数据结构被复制,指针操作的仍是同一块空间,感觉像是传引用

3.函数可以作为变量的值

4.函数可以作为参数和返回值

package fun_test

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

// 多个返回值
func returnMultiValues()(int, int)  {
    return rand.Intn(10), rand.Intn(20)
}

// 函数可以作为参数和返回值
// 计算inner函数运行的时间
func timeSpent(inner func(op int)int) func(opt 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, _ := returnMultiValues()
    t.Log(a)
    tsSF := timeSpent(slowFun)
    t.Log(tsSF(10))
}

结果:

=== RUN TestFn
time spent: 1.0000582
--- PASS: TestFn (1.00s)
func_test.go:32: 1
func_test.go:34: 10
PASS

待续-------------------------------------------------

猜你喜欢

转载自www.cnblogs.com/aidata/p/11875771.html