Functions
Declaring functions with typed parameters and results, and passing functions as values.
A function is a block of code that can take inputs and return results. It can have a name or be written inline. In Go, a function can also be stored in a variable or passed to another function, which lets code choose what work to run.
This example declares a function and gives it another function to call:
package main
import "fmt"
func double(n int) int {
return n * 2
}
func apply(value int, transform func(int) int) int {
return transform(value)
}
func main() {
fmt.Println(apply(4, double)) // 8
}In production
Keep helpers focused and return explicit values. For operations that can fail, Go commonly returns a value and an error; see Multiple Return Values.
Enjoyed this? Get more software craft delivered to your inbox.