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
}
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
andswitch
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.
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