3

3.2 Go语言中的匿名函数

 2 years ago
source link: https://sunqi.site/posts/old-sun-learning-go-notes-3-2/
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.

3.2 Go语言中的匿名函数

 2022-06-26  约 412 字   预计阅读 1 分钟    次阅读  

Go不允许函数嵌套,但是可以定义匿名函数,后续配合Goroutine的使用,很轻松的构建并发程序。

匿名函数一般是在函数体内的独立逻辑,与函数定义类似,但是由于其特殊位置,在使用时需要注意:

  • 在定义时主要为参数列表和返回值,如果不定义返回值类型,就不要使用return
  • 在定义的尾部不要忘了执行,即(),否则会看到定义未使用的提示(func literal evaluated but not used);当然在Go语言中我们是可以将函数整体复制给变量的,后续只需要变量后面加()执行即可
  • 与正常带返回值的函数一样,接受返回值的时候,需要提供一个变量
func(Parameter-list) (Return-Type){
// code..

// Use return statement if Return-Type are given
// if Return-Type is not given, then do not 
// use return statement
return
}()
package main

import "fmt"

func main() {
    func () {
        fmt.Println("Hello, World")
    }()
}
package main

import "fmt"

func main() {
    msg := func () string {
        return "Hello, World"
    }()

    fmt.Println(msg)
}
package main

import "fmt"

func main() {
    func (s string) {
        fmt.Println(s)
    }("Hello, World")
}

函数赋值给变量

package main

import "fmt"

func main() {
    myFunc := func (s string) {
        fmt.Println(s)
    }

    myFunc("Hello, World")
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK