Go语言基础06 _function

Go语言基础06 _function

函数在Go语言中是一等公民

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

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

defer 函数时 Go语言中类似于 java的 final一样的存在

package _func

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()) // 计算 从 start 到这里 花了多少时间
      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))
}

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,6))
}

func Clear(){
   fmt.Println("Clear resources.")
}

func TestDefer(t *testing.T){
   defer Clear()
   fmt.Println("Start")
   panic("err") // defer声明的 函数 会在最后执行 无论是否出错
   //defer Clear()
}
posted on 2021-09-13 17:13  OwlInTheOaktree  阅读(23)  评论(0编辑  收藏  举报