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:\goproject\src\main>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:\goproject\src\main>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:\goproject\src\main>go run hello.go
val1= 2

reference: https://www.cnblogs.com/wt645631686/p/9482512.html


本文来自:简书

感谢作者:stepinstep

查看原文:golang-匿名函数

相关阅读 >>

Golang 编码转换解决方案

10 Golang map的正确使用姿势

[系列] Go grpc hello world

Golang 如何安装包

分享Golang的一个丑陋实现

详解Golang ssh连接服务器(模拟交互terminal)

Go是开源语言吗?

手撸Golang 创建型设计模式 简单工厂

聊聊Gost的pager

手撸Golang 架构设计原则 迪米特法则

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...