Go has built-in support for multiple return values
. This feature is used often in idiomatic Go, for example to return both result and error values from a function.
Version
Go 1.18
Multiple Return Values
package main
import "fmt"
func main() {
a, b := swap(1, 2)
fmt.Println(a, b)
}
func swap(x, y int) (int, int) {
return y, x
}
Line 10
func swap(x, y int) (int, int) {
return y, x
}
(int, int)
: declare returning 2int
of the functionreturn y, x
: return 2int
separated by,
Line 6
a, b := swap(1, 2)
a, b
: multiple assignment from the function call
Ignore the Return Values
package main
import "fmt"
func main() {
_, b := swap(1, 2)
fmt.Println(b)
}
func swap(x, y int) (int, int) {
return y, x
}
Line 6
_, b := swap(1, 2)
_
: use the blank identifier_
to ignore the return value
Conclusion
- Multiple return values in Go is elegant and intuitive, we can also use
_
to ignore the return value