zoukankan      html  css  js  c++  java
  • 5.3 Go 匿名函数

    5.3 Go 匿名函数

    Go支持匿名函数,顾名思义就是没名字的函数。

    匿名函数一般用在,函数只运行一次,也可以多次调用。

    匿名函数可以像普通变量一样被调用。

    匿名函数由不带函数名字的函数声明函数体组成。

    package main
    
    import "fmt"
    
    func main() {
        //定义匿名函数,接收2个参数n1,n2,返回值int
        res := func(n1, n2 int) int {
            return n1 * n2
        }(10, 20) //匿名函数在此处调用,传参
        fmt.Println("res=", res)
    }
    

    匿名函数赋值给变量

    局部变量

    package main
    
    import "fmt"
    
    func main() {
    //局部变量n1
        n1 := func(a, b int) int {
            return a * b
        }
        fmt.Printf("n1的类型:%T
    ", n1)
        res := n1(10, 10)
        fmt.Println("res调用结果:", res)
    }
    

    全局变量

    package main
    
    import "fmt"
    //f1就是全局匿名函数
    var (
        f1 = func(n1, n2 int) int {
            return n1 * n2
        }
    )
    
    func test() int {
        return f1(10, 10)
    }
    func main() {
        res := f1(20, 20)
        fmt.Printf("res结果:%d
    ", res)
    
        res2 := test()
        fmt.Printf("res2结果:%d
    ", res2)
    }
  • 相关阅读:
    JS加密库
    异常处理
    uva 10673 Play with Floor and Ceil
    执⾏ Python 程序的三种⽅式----pycharm安装
    第⼀个 Python 程序
    认识 Python
    svg的使用
    elementUI中el-image显示不出来图片?img与el-image的区别
    类型转化与变量
    liunx
  • 原文地址:https://www.cnblogs.com/open-yang/p/11256841.html
Copyright © 2011-2022 走看看