mardi 28 août 2018

golang if initialization statement scoped to inner if block. Why?

I've found a bug in my code

func receive() (err error) {
    if v, err := produce(); err == nil {
        fmt.Println("value: ", v)
    }
    return
}

Error is never returning from this function, but I was absolutely sure it should.

After some testing I understood that err is redeclared in the if statement. More than that - all variables are always redeclared in short variable assignment inside if statement, despite they were declared before.

This is working code

func receive() (err error) {
    v, err := produce()
    if err == nil {
        fmt.Println("value: ", v)
    }
    return
}

Here is an example: https://play.golang.org/p/1AWBsPbLiI1

Seems like if statement

//some code
if <init_statement>; <expression> {}
//more code

is equivalent to

//some code
{
    <init_statement>
    if expression {}
}
//more code

So, my questions:

1) why existing variables are not used

2) why such scoping is not mentioned in documentation/language spec

3) why compiler doesn't say that no one returns a value

Aucun commentaire:

Enregistrer un commentaire