Go Parameters & Return Values
Parameters are the inputs of a function and return values are its outputs. Go has a few features here that many languages lack — most importantly multiple return values, which is how Go reports errors.
Parameters
Each parameter has a name followed by its type. When consecutive parameters share a type, you can write the type once.
package main
import "fmt"
func describe(name string, age int, city string) {
fmt.Printf("%s (%d) lives in %s\n", name, age, city)
}
// x, y and z are all float64
func average(x, y, z float64) float64 {
return (x + y + z) / 3
}
func main() {
describe("Lina", 34, "Oslo")
fmt.Println(average(4, 8, 9))
}Lina (34) lives in Oslo
7
Arguments are passed by value
Go always passes a copy of each argument. If a function changes its parameter, the caller's variable is unaffected. (Slices and maps contain references internally, so a function can change their elements — and pointers, covered later, let you change anything on purpose.)
package main
import "fmt"
func reset(n int) {
n = 0
}
func clearFirst(items []string) {
items[0] = ""
}
func main() {
score := 50
reset(score)
fmt.Println(score) // still 50
list := []string{"a", "b"}
clearFirst(list)
fmt.Printf("%q\n", list) // slice element changed
}50
["" "b"]
Multiple return values
A function can return several values. List the result types in parentheses. The caller receives them with a multi-variable assignment.
package main
import "fmt"
func divmod(a, b int) (int, int) {
return a / b, a % b
}
func minMax(nums []int) (int, int) {
lo, hi := nums[0], nums[0]
for _, n := range nums[1:] {
lo = min(lo, n)
hi = max(hi, n)
}
return lo, hi
}
func main() {
q, r := divmod(17, 5)
fmt.Println("quotient", q, "remainder", r)
lo, hi := minMax([]int{7, 2, 9, 4})
fmt.Println("min", lo, "max", hi)
_, onlyRemainder := divmod(10, 4) // ignore a value with _
fmt.Println(onlyRemainder)
}quotient 3 remainder 2
min 2 max 9
2
The most important use of multiple results is the value, error pattern: functions that can fail return their result plus an error, which is nil on success.
package main
import (
"errors"
"fmt"
)
func safeDivide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func main() {
if result, err := safeDivide(10, 4); err == nil {
fmt.Println("result:", result)
}
_, err := safeDivide(1, 0)
if err != nil {
fmt.Println("error:", err)
}
}result: 2.5
error: cannot divide by zero
Named return values
You can give result values names. They start as zero values, act like local variables, and a bare return returns their current values. Named results are useful as documentation, but bare returns in long functions hurt readability — use them sparingly.
package main
import "fmt"
func stats(values []float64) (sum, mean float64) {
for _, v := range values {
sum += v
}
mean = sum / float64(len(values))
return // returns sum and mean
}
func main() {
s, m := stats([]float64{2, 4, 9})
fmt.Println(s, m)
}15 5
Variadic functions
A final parameter written ...T accepts any number of arguments of type T. Inside the function it is a slice []T. To pass an existing slice, spread it with slice....
package main
import "fmt"
func sum(label string, nums ...int) {
total := 0
for _, n := range nums {
total += n
}
fmt.Println(label, len(nums), "numbers, total", total)
}
func main() {
sum("none:")
sum("three:", 1, 2, 3)
scores := []int{10, 20, 30, 40}
sum("slice:", scores...)
}none: 0 numbers, total 0
three: 3 numbers, total 6
slice: 4 numbers, total 100
fmt.Println itself is variadic: its signature is func Println(a ...any) (n int, err error).
| Feature | Syntax |
|---|---|
| Shared parameter type | func f(a, b int) |
| Multiple results | func f() (int, error) |
| Named results | func f() (n int, err error) |
| Variadic parameter | func f(xs ...int) |
| Spread a slice | f(list...) |
Tip: Return errors as the last result and check them right away with
if err != nil. You will see this pattern in every Go codebase.
Test yourself
How does a Go function return two values?
- Return an array
return a, bwith result types in parentheses- Use
yield - It cannot
Inside func f(nums ...int), what is the type of nums?
int[]int...int[...]int
If a function sets its int parameter to 0, what happens to the caller's variable?
- It becomes 0
- Nothing, the function got a copy
- Compile error
- It becomes nil