How to distinguish between assignment and declaration of values ​​from a function with multiple return data?

When fetching multiple returns from a function, what I get is that you can declare variables for values ​​on the fly using :=

or assign values ​​to already existing variables, just using =

. My problem arises when I want to assign one of the return values ​​to an already existing variable by declaring a new variable for another.

I currently solved this by simply assigning values ​​and declaring the required variables ( bar

in this case) ahead of time, like 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 cannot be created due to:

./app.go: 16: foo declared and not used

So, is it possible somehow to avoid declaring the declaration bar

separately?

+3


source to share


1 answer


In this case, you cannot use short variable declarations ":="

to reuse the variable foo

according to the spec :

Unlike regular variable declarations, declaring a short variable can override variables if they were originally declared earlier in the same block with the same type and at least one of the non-empty variables is new. As a consequence, re-styling can only appear in a short declaration with multiple variables. The Redeclaration does not introduce a new variable; it just assigns a new value to the original.

excluding ./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 is foo

declared in a block if

, this declaration will create a new variable shading the original variable foo

in the outer block, the override foo

will only happen if you declared foo

and updated it with a short declaration with multiple variables inside the same block .

func main() {
    var foo = "default"     
    foo, bar := getFooAndBar()
    fmt.Println(bar) //prints: Bar
    fmt.Println(foo) //prints: Foo
}

      

+5


source







All Articles