In Go, functions are treated as first-class citizens, allowing you to pass them as arguments, return them from other functions, and even create anonymous functions.
The Go compiler automatically recognizes the main
function we have used as the entry-point function where all relevant functions and operations are carried out.
By the rule of thumb, a project that must be built must have a main
function.
Let's see how other functions are written. Below is a basic function that has an input, an output, and a body. Here's an example:
package main
import "fmt"
// add accepts two input parameters of type int, and returns a single output of type int.
func add(a, b int) int {
return a + b
}
func main() {
// add function is called and used here.
result := add(10, 20)
fmt.Println("Sum:", result) // Output: Sum: 30
}
Just so you know, a function with output specified must have a return statement by the rule of thumb. Also, when calling a function, you must satisfy its required number of parameters to use it.
In Go, you can assign functions to variables and use them like any other variable. This is particularly useful when passing functions as arguments to other functions. In this example, we use a function variable to calculate the area of a rectangle:
package main
import "fmt"
type calculate func(float64, float64) float64
func rectangleArea(length, width float64) float64 {
return length * width
}
func main() {
var area calculate
area = rectangleArea
length, width := 5.0, 10.0
result := area(length, width)
fmt.Printf("Rectangle Area with length %.2f and width %.2f: %.2f\n", length, width, result)
// Output: Rectangle Area with length 5.00 and width 10.00: 50.00
}