[go学习笔记]十、Go语言的函数

240 阅读1分钟

函数一等公民

  • 可以有多个返回值
  • 所有参数都是值传递:slice,map,channel会有传引用的错觉
  • 函数可以作为变量的值
  • 函数可以作为参数和返回值

多返回值

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

func TestFn(t *testing.T) {
	a, _ := returnMultiValues()
	t.Log(a)
}

输出

=== RUN   TestFn
--- PASS: TestFn (0.00s)
    func_test.go:14: 1
PASS

Process finished with exit code 0

一个小实验,对一个函数添加耗时统计

package func_test

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

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

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, _ := returnMultiValues()
	t.Log(a)
	tsSF:=timeSpent(slowFun)
	t.Log(tsSF(10))
}

输出

=== RUN   TestFn
time spent: 1.00139513  <-----这里已经打印出来了总共耗时
--- PASS: TestFn (1.00s)
    func_test.go:31: 1
    func_test.go:33: 10
PASS

Process finished with exit code 0

以上例子就好像设计模式里边的装饰者模式,我们只是在原有函数的基础上包了一层,但是不去改变原来函数

示例代码请访问: github.com/wenjianzhan…