9

go语言之一等函数_zzxiaoma的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_3764469/5703570
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

go语言之一等函数

精选 原创

zzxiaoma 2022-09-22 15:28:33 博主文章分类:go ©著作权

文章标签 赋值 调用函数 返回函数 文章分类 Go语言 编程语言 yyds干货盘点 阅读数182

可以将函数赋值给变量,可以将函数传递给函数,甚至可以编写创建并返回函数的函数。

func add() int {
return 1 + 1
}


adds := add
fmt.Println(adds())

调用函数的时候需要用到圆括号,单这次的程序在赋值的时候并没有这样做,这里把add()赋给变量adds,通过adds()来调用函数。adds变量的类型是函数,具体来说就是一个不接收任何形参并且只返回一个值的函数。

因为变量既可以指向函数,又可以作为参数传递给函数,所以同样可以在go里面将函数传递给其他函数。

func add() int {
return 1 + 1
}

func addone(add func() int) int {
return add()
}

adds := add
fmt.Println(addone(adds))

这里addone函数中的参数就是一个函数,调用addone时,先把add函数赋予一个变量,然后这个变量当做addone中的参数进行调用。当然也可以直接传递add进行调用。

再看个返回函数的例子

type ok func() int

func okone(a ok) ok {
return func() int {
return a()
}
}

func add() int {
return 1 + 1
}

adds := add
me := okone(adds)
fmt.Println(me())

okone有一个函数参数,并且返回也是一个函数参数,返回的函数相当于调用的就是参数的函数。

还可以把匿名函数赋给变量,就像使用其他函数那样使用变量

f := func() {
fmt.Println("hello")
}
f()

也可以不赋予变量,直接在后面加入括号进行调用

func() {
fmt.Println("hello")
}()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK