Go 其四 函数

  艺多不压身,学习一下最近蛮火的Go语言,整理一下笔记。相关Code和笔记也放到了Git上,传送门

函数 -- 一等公民
与其他主要编程语言的差异

  1. 可以有多个返回值
  2. 所有参数都是值传递: slice, map, channel 会有传引用的错觉。以Slice举例,实际上是一个结构,传递过去的是指向具体内存的指针的值,所以操作的是同一个空间。看起来就像是传递的引用一样。
  3. 函数可以作为变量的值 (笔者注:看描述感觉类似于C#中的Delegate)
  4. 函数可以作为参数或返回值 (笔者注:感觉类似于C#中的Function与Action)

函数 可变参数及延迟运行

可变参数

func sum(ops ... int) int {
    s := 0
    for _, op := range ops {
        s += op
    }
    return s
}

 

延迟执行函数 defer 类似于Finnaly

 

func TestDefer(t *testing.T){
    defer func() { /*这个内联函数直到TestDefer执行完毕,返回前才会执行。 通常用于清    理资源,释放锁等功能*/
    t.Log("Clear resources")
    }()
    t.Log("Started")
    panic("Fatal error") //defer 仍会执行 //panic是Go中程序异常中断,抛出致命错误
}

 

附上代码:

package func_test

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

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

func slowFun(op int) int{
	time.Sleep(time.Second *1)
	fmt.Println("In SlowFun, the parameter is", op)
	return op
}


// 传递一个函数进来
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 TestFn(t *testing.T) {
	// 函数多个返回值
	a, b := returnMultiValues()
	t.Log(a, b)

	// 计算函数运行时间
	tsSF := timeSpent(slowFun)
	t.Log(tsSF(10))
}

func Sum (ops ... int) int {
	ret := 0
	for _, s := range ops {
		ret += s
	}
	return ret
}

func TestVarParam(t *testing.T) {
	t.Log(Sum(1,2,3,4))
	t.Log(Sum(5,6,7,8,9))
}

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

func TestDefer(t *testing.T){
	defer func() { //这个内联函数直到TestDefer执行完毕,返回前才会执行。 通常用于清理资源,释放锁等功能
		defer Clear()
		t.Log("Clear resources")
	}()
	t.Log("Started")
	panic("Fatal error") //defer 仍会执行 //panic是Go中程序异常中断,抛出致命错误
}

  

 

posted @ 2020-06-27 11:25  DogTwo  阅读(245)  评论(0编辑  收藏  举报