在 go lang 中使用“If with a short statement”有什么好处。引用:go tour
if v := math.Pow(x, n); v < lim {
return v
}
而不是只在 if
之前写语句。
v := math.Pow(x, n)
if v < lim {
return v
}
最佳答案
if v := math.Pow(x, n); v < lim
很有趣如果你不需要'v
'在'if
的范围之外'.
在“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
}
第二种形式允许' v
' 在 if
之后使用条款。
真正的区别在于您需要此变量的范围:在 if
中定义它子句允许将该变量的使用范围保持在最低限度。
关于if-statement - "If with a short statement"有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23649451/