if-statement - "If with a short statement"有什么好处

标签 if-statement go

在 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 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
}

第二种形式允许' v ' 在 if 之后使用条款。

真正的区别在于您需要此变量的范围:在 if 中定义它子句允许将该变量的使用范围保持在最低限度。

关于if-statement - "If with a short statement"有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23649451/

相关文章:

java - 在 if 语句中使用按位 &

go - 有没有办法从字符串创建结构的实例?

go - File.Readdir() 不能被调用多次?

r - 使用多个 if 条件

r - 如何对数据进行分类并绘制图表

pointers - 指向结构体的指针(或缺少结构体的指针)

database - 在 Go 中模拟数据库/sql 结构

xml - 如何使用golang编码/xml读取具有不同根的xml内容

php - 在 PHP 中获取一组行的程序具有相同的代码结构,但在另一行上没有结果

android - If 语句给出的条件始终为真