嵌套函数在Go语言中的表达方式如下:

huangapple go评论69阅读模式
英文:

nested functions in go

问题

我正在尝试在Go语言中声明一个嵌套函数:

package main
import "fmt"

func main() {
	func plus(x int, y int) int {
		return x+y
	}
}

但是Go编译器报错:

.\hello.go:6:7: 语法错误: 意外的 plus期望 (

错误出现在第6行的 return 语句。

有人可以帮我修复吗?

英文:

I am trying to declear func in func in go language:

package main
import "fmt"

func main() {
	func plus(x int, y int) int {
		return x+y
	}
}

And the go compiler say:

.\hello.go:6:7: syntax error: unexpected plus, expecting (

when line 6 is the line of the return.

Can someone help me fix it?

答案1

得分: 1

函数只能在包级别声明。如果你只想在外部函数内使用它,可以定义一个匿名函数并将其赋值给一个变量:

func main() {
    plus := func(x int, y int) int {
        return x+y
    }
}

尽管这种用法相对较少见。

英文:

Functions can only be declared at the package level. You could define an anonymous function and assign it to a variable if you only want to use it within the outer function:

func main() {
    plus := func(x int, y int) int {
        return x+y
    }
}

Though use cases for this are relatively rare.

huangapple
  • 本文由 发表于 2022年11月22日 02:33:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/74523441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定