What is the anonymous function in Go?

The anonymous function is a unique feature in Go; it doesn’t have any name. We call an anonymous function without any identifier, and we use it to create an inline function. A function literal is the term used for anonymous functions.

Syntax

func(parameter_list)(return_type){
// ("write your code here")
return
}()

In place of return_type, we can list the return type of values the function returns.

Anonymous function properties

  1. We can assign the function (anonymous) to a variable, and the variable type will be similar to the type of the function. We can call the variable as a function call.
package main
import "fmt"
func main(){
var1 := func(){
fmt.Println("Hello, World")
}
var1()
}
  • Line 1: We create a package main.
  • Line 2: We import the library fmt to use the print statement.
  • Line 6: We assign the anonymous function to the variable and make the variable callable.
  1. We can also pass arguments to the anonymous function.

func(arg1 string){
fmt.Println(arg1)
}("Welcome to Educative")
Passing argument to an anonymous function
  1. We can return an anonymous function from another function.
package main
import "fmt"
// Returning anonymous function
func dummy() func(arg string) string{
var1 := func(arg string)string{
return arg + "World"
}
return var1
}
func main() {
rvalue := dummy()
fmt.Println(rvalue("Hello "))
}
  • Line 7: The function dummy()'s return type is an anonymous function.
  • Line 8: The dummy() function returns an anonymous function.
  • Line 15: The rvalue is made callable by assigning a function dummy().

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved