为什么不检查nil上班?

Ben*_*ade 0 go

在第一个代码示例中,我收到"if pr!= nil"行的错误:

for sup, _ := range supervisorToColor {
        pr := emailToPerson[sup]
        // The line below causes the compilation error:
        // ./myprog.go:1046: missing condition in if statement
        // ./myprog.go:1046: pr != nil evaluated but not used
        if pr != nil 
        {   
          local := peopleOnFloor[pr.Email]
          sp := &Super{pr, local}
          names = append(names, sp) 
        }   
}   
Run Code Online (Sandbox Code Playgroud)

如果我注释掉nil check if语句,它编译好:

for sup, _ := range supervisorToColor {
        pr := emailToPerson[sup]
        // if pr != nil 
        // {
          local := peopleOnFloor[pr.Email]
          sp := &Super{pr, local}
          names = append(names, sp) 
        // }
}   
Run Code Online (Sandbox Code Playgroud)

起初我倾向于认为这是代码中早期的一些语法错误,但是当我注释掉这些行时它会起作用的事实使我认为它是另一回事.

emailToPerson的类型为map [string]*Person是struct的人

提前致谢.如果事实证明这非常简单,那就道歉了.

Tim*_*per 6

开放的大括号需要与以下行相同if:

if pr != nil { 
Run Code Online (Sandbox Code Playgroud)

来自分号Go规范:

形式语法使用分号";" 作为许多作品的终结者.Go程序可以使用以下两个规则省略大多数这些分号:

  1. 当输入被分解为令牌时,如果该令牌是,则在行的最终令牌之后立即自动将分号插入到令牌流中

    • 标识符
    • 整数,浮点,虚数,符文或字符串文字
    • 关键字之一break,continue,fallthrough,或者return
    • 运营商和分隔符中的一个++,--,),],或}
  2. 为了允许复杂语句占用一行,可以在结束" )"或" }" 之前省略分号.

这意味着您的代码相当于:

if pr != nil;
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)