In Go, functions can return multiple values. This can be useful in situations where you want to return multiple results from a single function, or if you want to return both the result of an operation and an error code.
Here’s an example of a function that returns two values:
package main
import "fmt"
func swap(x, y int) (int, int) {
return y, x
}
func main() {
a, b := swap(42, 13)
fmt.Println(a, b)
}
Output:
13 42
In this example, the swap
function takes two integers as arguments and returns their values in reverse order. The values are then assigned to two variables, a
and b
, using the multiple assignment syntax.
Multiple return values can also be used to return both the result of an operation and an error code. For example:
package main
import (
"fmt"
"strconv"
)
func parseInt(str string) (int, error) {
i, err := strconv.Atoi(str)
if err != nil {
return 0, err
}
return i, nil
}
func main() {
i, err := parseInt("42")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(i)
}
Output:
42
In this example, the parseInt
function takes a string as an argument and returns an integer and an error. The error value is nil
if the parsing was successful, and an error message otherwise. The returned values are then assigned to two variables, i
and err
, using the multiple assignment syntax. If the error is not nil
, the function prints an error message and returns.
In Go, you can also use the blank identifier _
to ignore one or more of the returned values if you don’t need to use them. For example:
package main
import (
"fmt"
"strconv"
)
func parseInt(str string) (int, error) {
i, err := strconv.Atoi(str)
if err != nil {
return 0, err
}
return i, nil
}
func main() {
_, err := parseInt("42")
if err != nil {
fmt.Println("Error:", err)
return
}
}
In this example, the first returned value from the parseInt
function is ignored by using the blank identifier _
.
It’s also worth noting that Go does not support returning multiple values from a single return statement. If you want to return multiple values, you must use separate return statements for each value. This makes it clear and explicit what values are being returned, and helps prevent bugs caused by accidentally returning the wrong number of values.
Leave a Reply