Anonymous Functions in Go

Anonymous Functions in Go

In this tutorial, we are going to discuss anonymous functions in the Go languageGo language provides a special feature known as an anonymous function.

An anonymous function is a function that doesn’t contain any name. It is useful when you want to create an inline function.

Anonymous Functions in Go

In the Go language, an anonymous function can form a closure. An anonymous function is also known as function literal.

Declaring Anonymous Functions

Declaration syntax for anonymous function is pretty straightforward. It is no different in syntax than a regular function.

Syntax

func(parameter_list)(return_type){
// code 
// Use return statement if return_type are given if return_type 
// is not given, then do not use return statement 
return 
}()
package main

import "fmt"

func main() {
    func() {
        fmt.Println("Welcome to Waytoeasylearn..!!")
    }()
}
Welcome to Waytoeasylearn..!!

Run in playground

In Go language, you are allowed to assign an anonymous function to a variable.

When you assign a function to a variable, then the type of the variable is of function type and you can call that variable like a function call as shown in the below example.

package main

import "fmt"

func main() {
    value := func() {
        fmt.Println("Welcome to Waytoeasylearn..!!")
    }
    value()
}

Run in playground

Please note that you can also pass arguments in the anonymous function.

package main

import "fmt"

func main() {
    func(message string) {
        fmt.Println(message)
    }("Welcome to Waytoeasylearn..!!")
}

Run in playground

You can also pass an anonymous function as an argument into other function.

package main 
 
import "fmt"

func print(i func(p, q string)string){ 
    fmt.Println(i ("Welcome ", "to ")) 
} 

func main() { 
    value:= func(p, q string) string{ 
        return p + q + "Waytoeasylearn..!!"
    } 
    print(value) 
} 

Run in playground

You can also return an anonymous function from another function.

package main 

import "fmt"

func display() func(i, j string) string{ 
    myf := func(i, j string)string{ 
        return i + j + "Waytoeasylearn..!!"
    } 
    return myf 
} 

func main() { 
    value := display() 
    fmt.Println(value("Welcome ", "to ")) 
} 

Run in playground

Please note that anonymous functions can accept inputs and return outputs, just as standard functions do.

That’s all about the Anonymous Functions in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!

Anonymous Functions in Go
Scroll to top