capypad
0 day streak
go / beginner
Snippet

Multiple Return Values and Named Results

Go functions can return multiple values, which is commonly used for returning a result alongside an error. This pattern makes error handling explicit and readable. You can also name the return values, which creates variables initialized to their zero values. The return statement without arguments returns these named variables. This is idiomatic Go for handling errors without exceptions.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
 
import "fmt"
 
func divide(a, b float64) (result float64, err error) {
if b == 0 {
err = fmt.Errorf("division by zero")
return // returns result and err
}
result = a / b
return // returns result and err
}
 
func main() {
quotient, err := divide(10, 3)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Result: %.2f\n", quotient)
 
q2, err2 := divide(5, 0)
if err2 != nil {
fmt.Println("Error:", err2)
}
}
Breakdown
1
(result float64, err error)
Function declares two return values: a quotient and an error
2
err = fmt.Errorf(...)
Creates an error when division by zero is attempted
3
quotient, err := divide(10, 3)
Receives both return values, err is nil on success
4
return // without arguments
Returns the named result and err variables