In Go, function literals (also known as anonymous functions or closures) enable you to define inline functions without names. The syntax of function literals is very similar to that of regular function definitions, but they can be assigned to variables or directly passed as parameters. Basic syntax is as follows:
gofunc(parameters) returnType { // Function body }
Here is a concrete example demonstrating how to create and use function literals:
gopackage main import "fmt" func main() { // Define the function literal and assign it to a variable add := func(x, y int) int { return x + y } // Call the function literal result := add(5, 7) fmt.Println("Result is:", result) }
In this example, we create an anonymous function that accepts two integer parameters and returns their sum, assigning it to the variable add. Then, we execute the function by calling the add variable.