Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of "If with a short statement"

What's the advantage of using an "If with a short statement" in go lang. ref: go tour

if v := math.Pow(x, n); v < lim {
    return v
}

Instead of just write the statement before the if.

v := math.Pow(x, n)
if v < lim {
    return v
}
like image 459
Zhen Avatar asked May 14 '14 08:05

Zhen


1 Answers

if v := math.Pow(x, n); v < lim is interesting if you don't need 'v' outside of the scope of 'if'.

It is mentioned in "Effective Go"

Since if and switch accept an initialization statement, it's common to see one used to set up a local variable.

if err := file.Chmod(0664); err != nil {
    log.Print(err)
    return err
}

The second form allows for 'v' to be used after the if clause.

The true difference is in the scope where you need this variable: defining it within the if clause allows to keep the scope where that variable is used to a minimum.

like image 101
VonC Avatar answered Oct 20 '22 01:10

VonC