When retrieving multiple returns from a function, I get that you can declare variables for the values on the fly by using :=
or assign the values to already existing variables by simply using =
. My issue occurs when I want to assign one of the return values to an already existing variable while declaring a new variable for the other.
I have currently solved it by only assigning the values and declaring the required variables (bar
in this case) beforehand, as in this snippet:
package main
import (
"fmt"
)
func getFooAndBar() (foo string, bar string) {
return "Foo", "Bar"
}
func main() {
var foo = "default"
var condition = true
if condition {
var bar string // Would like to avoid this step if possible
foo, bar = getFooAndBar()
fmt.Println(bar)
}
fmt.Println(foo)
}
If I use :=
it fails to build due to:
./app.go:16: foo declared and not used
So, is it possible to somehow avoid the step declaring bar
separately?