Functions
Declaring functions with typed parameters and results, and passing functions as values.
A function names its inputs and outputs with types. Go functions are values, so a function can be passed to another function as behavior.
This example declares a function and passes another function to it:
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.