WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Intermediate · question 30 of 100

What are anonymous functions in Go and how are they used?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

Anonymous functions, also known as lambda functions or closures, are functions in Go that do not have a formal name, meaning they are declared and used without being assigned to a specific identifier. Anonymous functions allow you to create one-time-use, simple, or short functions that don’t need to be referred to multiple times.

An anonymous function is defined with the ‘func‘ keyword, just like a normal function, but without a name for the function, and it ends with a pair of parentheses followed by the function body enclosed in curly braces. The advantage of using anonymous functions is that they can be defined and executed within the same scope or context, making the code more concise and, in some cases, more efficient.

Here’s an example of an anonymous function in Go:

package main

import (
  "fmt"
)

func main() {
  // Declare and call an anonymous function
  func() {
    fmt.Println("Hello, anonymous function!")
  }()
}

To illustrate how they are used in real-world scenarios, let’s take a look at a couple of examples.

**Example 1: Using anonymous functions as arguments**

You can pass anonymous functions as arguments to other functions:

package main

import (
  "fmt"
)

// Function that takes a func() as input
func callFunction(f func()) {
  f()
}

func main() {
  // Create an anonymous function
  anonFunc := func() {
    fmt.Println("Hello from anonymous function.")
  }

  // Pass the anonymous function as an argument
  callFunction(anonFunc)
}

This will output:

Hello from anonymous function.

**Example 2: Anonymous functions with closures**

Closure is a feature of anonymous functions in Go that allows them to capture and store references to variables from their enclosing scope. This makes it possible to create self-contained, stateful functions that can manipulate the values of those captured variables. Here’s an example:

package main

import (
  "fmt"
)

// Function returning an anonymous function
func createCounter() func() int {
  count := 0

  return func() int {
    count++
    return count
  }
}

func main() {
  // Create a counter using the closure
  counter := createCounter()

  fmt.Println("Counter:", counter()) // 1
  fmt.Println("Counter:", counter()) // 2
  fmt.Println("Counter:", counter()) // 3
}

This will output:

Counter: 1
Counter: 2
Counter: 3

In this example, the ‘createCounter‘ function returns an anonymous function that captures the ‘count‘ variable. The anonymous function increments and returns the value of ‘count‘ every time it is called. Because of the closure, each invocation of the returned function can access and modify the ‘count‘ variable from its outer scope, even if the outer function (‘createCounter‘) has already completed its execution.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics