nested functions in go

Issue

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?

Solution

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.

Answered By – Adrian

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.