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
- 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 mainimport "fmt"func main(){var1 := func(){fmt.Println("Hello, World")}var1()}
- Line 1: We create a package
main. - Line 2: We import the library
fmtto use the print statement. - Line 6: We assign the anonymous function to the variable and make the variable callable.
- We can also pass arguments to the
anonymousfunction.
func(arg1 string){fmt.Println(arg1)}("Welcome to Educative")
Passing argument to an anonymous function
- We can return an
anonymousfunction from another function.
package mainimport "fmt"// Returning anonymous functionfunc 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
rvalueis made callable by assigning a functiondummy().
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved