Anonymous function in Go Language (original) (raw)

Last Updated : 29 Oct, 2024

An anonymous function is a function that doesn’t have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal.

Example

Go `

package main import "fmt"

func main() { // Anonymous function func() { fmt.Println("Welcome! to GeeksforGeeks") }() }

`

Output

Welcome! to GeeksforGeeks

Syntax:

func(parameter_list)(return_type) {
// code..

// Use return statement if return_type is given  
// if return_type is not given, then do not   
// use return statement  
return  

}()

Assigning to a Variable

You can assign an anonymous function to a variable. This variable can then be called like a regular function.

Go `

package main import "fmt"

func main() { // Assigning an anonymous function to a variable value := func() { fmt.Println("Welcome! to GeeksforGeeks") } value() }

`

Output

Welcome! to GeeksforGeeks

Passing Arguments

Anonymous functions can accept arguments.

Go `

package main import "fmt"

func main() { // Passing arguments in anonymous function func(ele string) { fmt.Println(ele) }("GeeksforGeeks") }

`

Passing as Arguments

You can also pass an anonymous function as an argument to another function.

Go `

package main import "fmt"

// Passing anonymous function as an argument func GFG(i func(p, q string) string) { fmt.Println(i("Geeks", "for")) } func main() { value := func(p, q string) string { return p + q + "Geeks" } GFG(value) }

`

Returning Anonymous Functions

You can return an anonymous function from another function.

Go `

package main import "fmt"

// Returning anonymous function func GFG() func(i, j string) string { myf := func(i, j string) string { return i + j + "GeeksforGeeks" } return myf }

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

`

Output

Welcome to GeeksforGeeks

Conclusion

Anonymous functions in Go are versatile and powerful. They can be used for creating inline functions, closures, and even for passing and returning functions. Understanding how to use them effectively can greatly enhance your programming in Go.