Anonymous Functions in Golang
An anonymous function is a function that was declared without any named identifier to refer to it. Anonymous functions can accept inputs and return outputs, just as standard functions do.
Assigning function to the variable.
Anonymous functions can be used for containing functionality that need not be named and possibly for short-term use.Example
package main
import "fmt"
var (
area = func(l int, b int) int {
return l * b
}
)
func main() {
fmt.Println(area(20, 30))
}
Example
Passing arguments to anonymous functions.
package main
import "fmt"
func main() {
func(l int, b int) {
fmt.Println(l * b)
}(20, 30)
}
Example
Function defined to accept a parameter and return value.
package main
import "fmt"
func main() {
fmt.Printf(
"100 (°F) = %.2f (°C)\n",
func(f float64) float64 {
return (f - 32.0) * (5.0 / 9.0)
}(100),
)
}
Most Helpful This Week
Simple function with parameters in Golang
Closures Functions in Golang
Golang Functions Returning Multiple Values
Creating a Function in Golang
Simple function with return value in Golang
Higher Order Functions in Golang
The return values of a function can be named in Golang
Golang Passing Address to a Function
What is Function in Golang
Naming Conventions for Golang Functions
User Defined Function Types in Golang