doumengwei0138 2014-06-19 23:47
浏览 16
已采纳

为什么在“ if”语句中使用语句?

The Go tour shows an example where they have an extra statement in the same line as the "if" statement and they explain it like this: the if statement can start with a short statement to execute before the condition.

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

I don't see the need for this syntax and find it very confusing. Why not just write v := math.Pow(x, n) in the previous line?

The reason I'm asking is that for what I'm finding out, syntax finds its way into the Go language after careful consideration and nothing seems to be there out of whim.

I guess my actual question would be: What specific problem are they trying to solve by using this syntax? What do you gain by using it that you didn't have before?

  • 写回答

2条回答 默认 最新

  • duangan6731 2014-06-19 23:59
    关注

    There are many use cases and I do not think this feature tackles a specific problem but is rather a pragmatic solution for some problems you encounter when you code in Go. The basic intentions behind the syntax are:

    • proper scoping: Give a variable only the scope that it needs to have
    • proper semantics: Make it clear that a variable only belongs to a specific conditional part of the code

    Some examples that I remember off the top of my head:

    Limited scopes:

    if v := computeStuff(); v == expectedResult {
        return v
    } else {
        // v is valid here as well
    }
    
    // carry on without bothering about v
    

    Error checking:

    if perr, ok := err.(*os.PathError); ok {
        // handle path error specifically
    }
    

    or more general, Type checking:

    if someStruct, ok := someInterface.(*SomeStruct); ok {
        // someInterface is actually a *SomeStruct.
    }
    

    Key checking in maps:

    if _, ok := myMap[someKey]; ok {
        // key exists
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误
  • ¥20 cesm的气溶胶排放文件
  • ¥15 逐月累计,月份不连续,补齐月份
  • ¥15 应用简单的Python代码完成一个学生成绩管理系统
  • ¥15 用matlab求微分方程初值问题
  • ¥15 vscode下编写第三方库opencv与pcl代码时没有代码提示
  • ¥15 能够跑通不报错,如何解决?(标签-matlab)
  • ¥15 MOS在RDS较大,频率高时开关波形异常
  • ¥15 SCENIC分析报错求解答