Go -- 函数

栏目: Go · 发布时间: 4年前

内容简介:函数可以作为延迟运行,类似于Java中的
  1. 可以有 多个返回值
  2. 所有参数都是 值传递 :slice、map、channel会有传引用的错觉
  3. 一等公民
    • 函数可以作为 变量的值
    • 函数可以作为 参数返回值

多返回值

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

func TestReturnMultiValues(t *testing.T) {
    a, b := returnMultiValues()
    t.Log(a, b) // 1 7
}

一等公民

函数可以作为 参数返回值

// 入参:func(op int) int
// 出参:func(op int) int
func timeSpent(inner func(op int) int) func(op int) int {
    // 函数式编程
    return func(op int) int {
    	start := time.Now()
    	ret := inner(op)
    	fmt.Println("time spent : ", time.Since(start).Seconds())
    	return ret
    }
}

func slowFunc(op int) int {
    time.Sleep(time.Second * 1)
    return op
}

func TestFuncAsParam(t *testing.T) {
    // f是通过函数式编程封装后的函数,增强了原有函数的功能
    f := timeSpent(slowFunc)
    t.Log(f(10))

    // 输出:
    // time spent :  1.004157729
    // 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)) // 10
}

defer

延迟运行,类似于 Java 中的 finally ,主要用于释放某些资源

func TestDefer(t *testing.T) {
    defer clear()
    fmt.Println("Start")
    panic("Fatal Error") // 依然会执行clear()
    fmt.Println("End")   // 不可达

    //	Start
    //	Clear Resources.
    //	--- FAIL: TestDefer (0.00s)
    //	panic: Fatal Error [recovered]
    //	panic: Fatal Error
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A=B

A=B

Marko Petkovsek、Herbert S. Wilf、Doron Zeilberger / AK Peters, Ltd. / 1996-01 / USD 49.00

At some point, this book describes methods of solving the problem raised by Donald E. Knuth in the classical book "The Art of Computer Programming, Volume 1: Fundamental Algorithms". The main purpo......一起来看看 《A=B》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码