Anonymous functions in Go are very useful. Here is the syntax, usage and example of using anonymous functions in Golang .

An anonymous function is a function that has no name. It is useful when you want to create an inline function. In Go, anonymous functions can also form a closure. Anonymous functions are also called function literals.
For example:
package main
import "fmt"
func main() {
// Hàm ẩn danh
func() {
fmt.Println("Welcome! to Quantrimang.com")
}()
}
Result:
Welcome! to Quantrimang.com
Syntax:
func(parameter_list)(return_type) {
// code..
// Dùng lệnh return nếu return_type được đưa ra
// nếu return_type không được cung cấp, thì không
// dùng lệnh return
return
}()
Assign a variable
You can assign an anonymous function to a variable. This variable can then be called like a regular function.
package main
import "fmt"
func main() {
// Gán một hàm ẩn danh cho một biến
value := func() {
fmt.Println("Welcome! to Quantrimang.com")
}
value()
}
Result:
Welcome! to Quantrimang.com
Pass as argument
You can also pass an anonymous function as an argument to another function.
package main
import "fmt"
// Chuyển hàm ẩn danh làm đối số
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)
}
Result:
GeeksforGeeks
Return anonymous function
You can return an anonymous function from another function.
package main
import "fmt"
// Trả về hàm ẩn danh
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 "))
}
Result:
Welcome to GeeksforGeeks
Conclude
Anonymous functions in Golang are very flexible and powerful. They can be used to create inline functions, closures, and even to pass and return functions. Understanding how to use them effectively can greatly improve your programming skills in Go.