Skip to content

Function Definitions

In Go functions are declared using the func keyword:

function.go
func myFunction() {
fmt.Println("Hello, World!")
}

This is similar to JavaScript/TypeScript, but with a few differences in syntax and usage.

Like JavaScript/TypeScript, Go also supports anonymous functions.

anonymous_function.go
func main() {
myFunc := func() {
fmt.Println("Hello from an anonymous function!")
}
myFunc()
}

Immediately Invoked Function Expressions (IIFE)

Section titled “Immediately Invoked Function Expressions (IIFE)”

It’s possible to define an anomymous function and immediately execute it, similar to IIFE’s.

iife.go
func main() {
func() {
fmt.Println("Hello from an IIFE!")
}()
}

Common when you deal with more advanced Go features like channels.