---
title: "How do you create and use anonymous functions in Go?"  
description: "How do you create and use anonymous functions in Go?"  
author: "Ravi Vishwakarma"  
published: 2025-04-01  
updated: 2025-04-07  
canonical: https://www.mindstick.com/forum/161401/how-do-you-create-and-use-anonymous-functions-in-go  
category: "programming language"  
tags: ["Go Programming"]  
reading_time: 2 minutes  

---

# How do you create and use anonymous functions in Go?

How do you create and use [anonymous](https://www.mindstick.com/interview/1140/what-is-anonymous-class-in-java) [functions](https://www.mindstick.com/forum/160140/explain-the-role-of-functions-as-a-service-faas-in-serverless-computing) in Go?

## Replies

### Reply by Khushi Singh

The **Go language** enables anonymous functionalities that let developers define unnamed functions as literals. Anonymous functions serve two purposes in Go for encapsulating expressions that do not require reuse or as function arguments. Go allows users to assign anonymous functions to variables as well as pass them as arguments to functions and execute them directly (also known as IIFE – Immediately Invoked Function Expression).

In Go language development, you define anonymous functions by using the `func` keyword directly followed by the function parameters without a name declaration. The syntax allows you to specify parameters together with the return type as you would in a normal function definition. Anonymous functions provide an efficient solution for creating brief logical statements together with inline statements.

## An example demonstrates the creation and utilization of Go anonymous functions as shown below:

```plaintext
package main
import "fmt"
func main() {
   // Assigning an anonymous function to a variable
   add := func(a int, b int) int {
       return a + b
   }
   // Using the function
   result := add(5, 7)
   fmt.Println("Sum:", result)
   // Immediately invoking an anonymous function
   func(message string) {
       fmt.Println("Message:", message)
   }("Hello from anonymous function")
}
```

The add variable contains an anonymous function that accepts two integers as well as returns their summed result. The function can be invoked through the same method used to call named functions. The second function operates as an immediate invocation since it receives its definition and execution in the same statement, making it useful for temporary operations.

Anonymity functions in Go create versatile tools for dealing with transient procedures and closures, and callbacks, which enhance developer capability to build modular and clean code.


---

Original Source: https://www.mindstick.com/forum/161401/how-do-you-create-and-use-anonymous-functions-in-go

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
