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?
In this case you can't use the short variable declarations ":=" for redeclaring the foo variable, according to the spec:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
by eliminating ./app.go:16: foo declared and not used.
func main() {
var foo = "default"
var condition = true
if condition {
foo, bar := getFooAndBar()
fmt.Println(bar) // prints: Bar
fmt.Println(foo) // prints: Foo
// _ = foo
}
fmt.Println(foo) // prints: default
}
in this case foo is declared in the if block, this declaration will create a new variable shadowing the original foo variable in the outer block, the redeclaration of foo will happen only if you have declared foo and redeclared it with multi-variable short declaration within the same block.
func main() {
var foo = "default"
foo, bar := getFooAndBar()
fmt.Println(bar) //prints: Bar
fmt.Println(foo) //prints: Foo
}
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