1. Introduction
Go language supports anonymous functions, which can be handy for creating closures or for defining a function inline without having to name it. These functions are useful when you want to define a function quickly without the need to reuse it elsewhere. In this blog post, we will demonstrate how to use an anonymous function in Go.
Definition
An anonymous function is a function that is defined without a name. While regular functions are defined using the func keyword followed by a name, anonymous functions are defined using the func keyword followed by a function signature and body.
2. Program Steps
1. Define the main function which serves as the entry point of the program.
2. Within the main, define an anonymous function that adds two numbers and prints the result.
3. Immediately invoke the anonymous function with arguments.
3. Code Program
package main
import "fmt"
func main() {
// Define and invoke an anonymous function.
func(a, b int) {
sum := a + b
fmt.Println("Sum:", sum)
}(3, 4) // Pass 3 and 4 as arguments to the anonymous function
}
Output:
Sum: 7
Explanation:
1. package main - This line sets the package for the program, which is main here, indicating an executable program.
2. import "fmt" - This imports the fmt package, which is used for formatted I/O operations, similar to C's printf or scanf.
3. In func main(), the main function is defined which will be the entry point when the program is executed.
4. Inside the main function, an anonymous function is defined using func(a, b int) { ... }. It takes two int parameters.
5. The body of the anonymous function calculates the sum of a and b and stores it in the sum variable.
6. The anonymous function is immediately invoked with 3 and 4 as arguments. This is known as an Immediately Invoked Function Expression (IIFE).
7. The fmt.Println function is called to print the sum, which outputs Sum: 7.
Comments
Post a Comment