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

    概念
    所谓匿名函数,就是没有名字的函数
    匿名函数的两种使用方式
    一、在定义匿名函数的时候就可以直接使用(这种方式只使用一次)

    package main
    import (
        "fmt"
    )
    func main(){
        res1 := func (n1 int, n2 int) int {
            return n1 + n2
        }(10, 30)  //括号里的10,30 就相当于参数列表,分别对应n1和n2
        
        fmt.Println("res1=",res1)
    }
    D:goprojectsrcmain>go run hello.go
    res1= 40

    二、将匿名函数赋给一个变量(函数变量),再通过该变量来调用匿名函数

    package main
    import (
        "fmt"
    )
    func main(){
        //将匿名函数fun 赋给变量test_fun
        //则test_fun的数据类型是函数类型,可以通过test_fun完成调用
        test_fun := func (n1 int, n2 int) int {
            return n1 - n2
        }
    
        res2 := test_fun(10, 30)
        res3 := test_fun(50, 30)
        fmt.Println("res2=", res2)
        fmt.Println("res3=", res3)
        fmt.Printf("%T", test_fun)
    }
    D:goprojectsrcmain>go run hello.go
    res2= -20
    res3= 20
    func(int, int) int

    全局匿名函数

    全局匿名函数就是将匿名函数赋给一个全局变量,那么这个匿名函数在当前程序里可以使用

    package main
    import (
        "fmt"
    )
    
    //Test_fun 就是定义好的全局变量
    //全局变量必须首字母大写
    var (
        Test_fun = func (n1 int, n2 int) int {
            return n1 - n2
        }
    )
    func main(){
        val1 := Test_fun(9, 7)
    
        fmt.Println("val1=", val1)
    }
    D:goprojectsrcmain>go run hello.go
    val1= 2
  • 相关阅读:
    git学习
    Command Line
    python之测试
    python之模块
    python之函数
    python之类
    python之错误和异常
    python之迭代器和生成器
    python之字典和集合
    python之列表和元组
  • 原文地址:https://www.cnblogs.com/wt645631686/p/9482512.html
Copyright © 2011-2022 走看看