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条)

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效