Given swap
, a function that returns multiple values, and supposing it's part of some API I can't modify:
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Is it possible to use swap
function and get only the first returned value, discarding the second one? I tried this:
func main() {
a, b := swap("hello", "world")
fmt.Println(a)
}
ERROR: prog.go:10: b declared and not used [process exited with non-zero status]
And this is not possible too:
a := swap("hello", "world")
ERROR: prog.go:10: multiple-value swap() in single-value context
How to deal with functions that return multiple values when I don't need all the returned parts?
Code is based on "A tour of go - lesson 9"
Use the blank identifier _
:
a, _ := swap("hello", "world")
Everything assigned to the blank identifier is silently discarded without a warning being raised. You can also use the blank identifier to add padding to structures:
struct {
a byte
b byte
c byte
_ byte // padding
}
Another usage of the blank identifier is to discard return values when initializing global variables:
var foo, _ = foo.NewFoo() // ignore error returned by NewFoo()
And when only one value of a range is required:
for _, v := range mySlice { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With