Functions in Go
| Define and call | |
| Parameters | |
| Multiple return values | |
| Named results |
Define and call
A function packages a reusable step behind a name: define it once with func, then call it wherever the step is needed. Go programs start in main, so even tiny examples define helpers and call them from there.
package main
import "fmt"
func greet() {
fmt.Println("Hello from Go")
}
func main() {
greet()
}
go run main.go
Hello from Go
Helpers can sit above or below main in the file: Go does not care about definition order. Name functions after what they do, starting with a verb for actions and a noun for computed values.
Parameters
Parameters listed in the header receive a copy of each argument at every call. Types follow the names, and neighbors can share one type written once, as in add(a int, b int).
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
fmt.Println(add(2, 3))
}
5
The trailing int after the parentheses is the result type: every return in the body must hand back an int. Because arguments arrive as copies, changing a parameter inside never affects the caller.
Multiple return values
Go functions may return several values at once, which removes the need for output parameters or tiny wrapper structs. Callers unpack the results with one short declaration.
package main
import "fmt"
func split(total int) (int, int) {
return total / 2, total - total/2
}
func main() {
half, rest := split(7)
fmt.Println(half, rest)
}
3 4
Keep multi value returns to two or three results: beyond that a small struct with named fields reads better. The next lesson shows how the second result often carries an error.
Named results
Results can carry names, turning them into variables that start at their zero values. A bare return then hands back whatever the named results hold, which reads well for short functions with several exit points.
package main
import "fmt"
func rect(w int, h int) (area int, perim int) {
area = w * h
perim = 2 * (w + h)
return
}
func main() {
fmt.Println(rect(3, 4))
}
12 14
Keep named results for short bodies: in long functions explicit return values stay easier to follow. Either style compiles to the same code, so pick the one that reads best.
Next: Errors as values
Article author: Arthur Isaev