Writing function inside and outside of func main()

Snipper inside

package main
import "fmt"

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

	fmt.Println(add(42, 13))
}

Snipper outside

package main

import "fmt"

func add(x int, y int) int {
	return x + y
}

func main() {

	fmt.Println(add(42, 13))
}

As you can see in order to put add inside func main I had to use the add := func syntax. However I don’t understand why this doesn’t work:

package main
import "fmt"

func main() {

	func add(x int, y int) int {
		return x + y
	}
	
	fmt.Println(add(42, 13))
}

This gives me an error: prog.go:6:7: syntax error: unexpected add, expecting (

Same error if I put it outside but use the := syntax:

package main

import "fmt"

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

func main() {

	fmt.Println(add(42, 13))
}

Error: prog.go:5:5: syntax error: unexpected :=, expecting name

Any ideas?

1 Like

In the first case, you can’t declare a function inside another one, Go doesn’t allow nested functions. But as you saw, you can declare a variable whose value is a function. That’s because in Go functions are first class members, i.e., they are actual types and thus you can declare function literals.

In the second case, that’s because the declare and assign syntax := isn’t allowed at the top level, but it’s perfectly fine to do this:

package main

import "fmt"

var add = func(x int, y int) int {
	return x + y
}

func main() {
	fmt.Println(add(42, 13))
}

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.