go lang中使用"If with a short statement"的优点是什么?参考:去旅游
if v := math.Pow(x, n); v < lim {
return v
}
Run Code Online (Sandbox Code Playgroud)
而不只是在之前写下声明if.
v := math.Pow(x, n)
if v < lim {
return v
}
Run Code Online (Sandbox Code Playgroud)
Von*_*onC 15
if v := math.Pow(x, n); v < lim有趣的是,如果你不需要" v"的范围之外" if".
在" Effective Go "中提到它
由于
if和switch接受初始化语句,它经常可以看到一个用于设置一个局部变量.
if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
Run Code Online (Sandbox Code Playgroud)
第二种形式允许v在该if条款之后使用' ' .
在真正的区别在于,你需要这个变量的范围:在中定义它if子句允许保持如该变量用于最小范围.