CodeBlanks Logo Icon CodeBlanks

Anonymous functions

Learn anonymous functions and the closure concept.

Anonymous functions

Functions without a name can be assigned to a variable, passed as an argument or called right away:

kare := func(n int) int { return n * n }
fmt.Println(kare(4))  // 16

func() {
    fmt.Println("hemen çalıştı")
}()

In Go functions are first-class values: they have types (func(int) int) and are passed around like other values.

A counter with a closure

A function can return another function that captures its local variable. The captured variable is updated on every call:

func sayacYap() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}

say := sayacYap()
fmt.Println(say(), say(), say())  // 1 2 3

Every sayacYap() call creates its own independent n.

Practice Closure counter

Write the sayacYap function above. Create two separate counters (a and b); call a twice and b once, then print the next values with fmt.Println(a(), b()).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func sayacYap() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}

func main() {
    a := sayacYap()
    b := sayacYap()
    a()
    a()
    b()
    fmt.Println(a(), b())
}

Expected output

3 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is a closure?

  • A function invisible outside the package
  • An anonymous function that captures and uses outside variables Correct answer
  • A function that ends the program
  • A function without parameters

Explanation: A closure accesses the variables where it was defined by reference and keeps them alive even after the outer function returns.

2 Function type

Question
func sayacYap() ____ int {
    n := 0
    return func() int { n++; return n }
}
Answer
func sayacYap() func() int {
    n := 0
    return func() int { n++; return n }
}

Explanation: The return type func() int is a function with no parameters that returns an int.

3 Code and meaning

Term Meaning
func(n int) int {...} A function value
func() {...}() Called immediately
n++ (yakalanan) Closure state
func() int A function type

All lessons in Beginner