Go Functions Literal functions & closures

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A simple literal function, printing Hello! to stdout:

package main

import "fmt"

func main() {
    func(){
        fmt.Println("Hello!")
    }()
}

play it on playground


A literal function, printing the str argument to stdout:

package main

import "fmt"

func main() {
    func(str string) {
        fmt.Println(str)
    }("Hello!")
}

play it on playground


A literal function, closing over the variable str:

package main

import "fmt"

func main() {
    str := "Hello!"
    func() {
        fmt.Println(str)
    }()
}

play it on playground


It is possible to assign a literal function to a variable:

package main

import (
    "fmt"
)

func main() {
    str := "Hello!"
    anon := func() {
        fmt.Println(str)
    }
    anon()
}

play it on playground



Got any Go Question?