美文网首页
【Go - 常见的5类函数用法】

【Go - 常见的5类函数用法】

作者: wn777 | 来源:发表于2024-07-09 00:31 被阅读0次

函数

函数通过func关键字定义,后跟函数名、参数列表、返回类型。语法如下:

func functionName(parameters) returnType {
    // 函数体
}

示例

func add(x int, y int) int {
    return x + y
}

func swap(x, y string) (string, string) {
    return y, x
}

变参函数

func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}

匿名函数

    s := (func () string {
        return "anonymous-function"
    })()
    fmt.Println(s)

高阶函数,函数作为参数和返回值

函数也可以作为参数传入 或者 作为返回值传出

// 函数作为参数
func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

// 函数作为返回值
func getComputeFunc() func(int, int) int  {
   return func(x, y int) int {
       return x + y
   }
}

闭包


func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

// 调用
func main() {
    incfunc := intSeq()
    fmt.Println(incfunc())
    fmt.Println(incfunc())
}

闭包本质是对作用域的延伸。
就比如intSeq中的i,如果没有其它地方引用,其会被垃圾回收,但是由于incfunc中有对其的引用,其不能被回收,其生命周期变长了,作用域延伸了。

相关文章

  • Excel常见函数常见用法

    Excel 常用函数 在Excel函数中 出现 A:A 表示A列,出现A1 表示 A1这个单元格。 1、SUM 2...

  • Kotlin 作用域函数

    目录 作用域函数分析 常见作用域函数with,apply,also,let,run,with 作用域函数用法 1....

  • 常见损失函数用法

    损失函数(loss function)又叫做代价函数(cost function),是用来评估模型的预测值与真实值...

  • matplotlib常见函数用法

    1.subplot matplotlib 中的subplot的用法 - 学弟1 - 博客园 Python Matp...

  • GeoTools常见函数用法

    GeoTools is an open source Java library that provides too...

  • go select + channel 常见用法

    for-select for-select 是一个很常见的用法,select 语句可以从多个可读的 channel...

  • Python3 中逗号的特殊用法

    常见用法: 1. 作为参数或变量的分隔符 不常见用法: 2. 在print函数中的应用,使得输出不换行 3. 将变...

  • 哈希算法

    哈希算法 什么是hash函数?常见的hash算法hashlib的用法hash算法的用途 什么是hash函数? 哈希...

  • python序列

    1、列表 列表的结构就是我们平常见的数组,常见用法如下 直接创建 aa=[] 使用list函数 list('hel...

  • jQuery中常见函数用法

    .val().attr().removeAttr().prop().css().addClass().remove...

网友评论

      本文标题:【Go - 常见的5类函数用法】

      本文链接:https://www.haomeiwen.com/subject/fzmacjtx.html