dongqiu8375 2016-06-14 21:05
浏览 10
已采纳

语句块进入

I'm not sure what the correct name for it is (and thus how to search for it), but I was just looking through some go code and saw it organized with statements inside of {}'s. I'm wondering what the reason is for supporting grouping statements like this?

The code looks like this:

// Check horizontal
{
    left_to_win := 3

    stop_1 := false
    stop_2 := false
    for x := 1; x <= 4; x++ {
        // ....
    }
}

// Check vertical
{
    left_to_win := 3

    stop_1 := false
    stop_2 := false

    for x := 1; x <= 4; x++ {
        // ...
    }
}

// Check diagonal bottom to top
{
    left_to_win := 3

    stop_1 := false
    stop_2 := false

    for x := 1; x <= 4; x++ {
        // ...
    }
}

In the specific example it seems like it could easily be refactored into a single utility function. What's the name of this feature, and are there any good examples of times to use it?

  • 写回答

1条回答 默认 最新

  • douzhi2012 2016-06-14 21:34
    关注

    Those braces are defining a more specific scope for local variables. In your case each scope is declaring stop_1, stop_2 and left_to_win. Without the additional curly braces you would get a compiler error saying you're redeclaring or defining those variables since you're using the short hand := which declares and assigns in one statement.In this case the code could be written to instead just use := on the initial declaration and then = for subsequent assignment which would remove the need for those scopes defined by the curly braces.

    See here for more details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私