[英]Why doesn't this check for nil in go work?
In the first code example, I get errors for the "if pr != nil" line: 在第一个代码示例中,出现“ 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)
}
}
If I comment out the nil check if statement, it compiles fine: 如果我注释掉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)
// }
}
At first I was inclined to think it was some syntax error earlier in the code, but the fact that it works when I comment out the lines makes me think it's something else. 起初,我倾向于认为这是代码较早的语法错误,但是当我注释掉这些行时,它确实起作用,这使我觉得这是另一回事。
emailToPerson is of type map[string]*Person where Person is a struct emailToPerson的类型为map [string] * Person,其中Person是结构
Thanks in advance. 提前致谢。 Apologies if this turns out to be something incredibly simple.
抱歉,这真是太简单了。
The open curly brace needs to be on the same line as the if
: 大括号必须与
if
位于同一行:
if pr != nil {
From the Go spec on semicolons : 从分号的Go规范中 :
The formal grammar uses semicolons ";"
形式语法使用分号“;” as terminators in a number of productions.
作为许多作品的终结者。 Go programs may omit most of these semicolons using the following two rules:
Go程序可以使用以下两个规则来省略大多数这些分号:
When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is
当输入分解为令牌时,如果该行是令牌,则在该行的最终令牌之后立即将分号自动插入令牌流中
- an identifier
标识符
- an integer, floating-point, imaginary, rune, or string literal
整数,浮点数,虚数,符文或字符串文字
- one of the keywords
break
,continue
,fallthrough
, orreturn
关键字的一个
break
,continue
,fallthrough
,或return
- one of the operators and delimiters
++
,--
,)
,]
, or}
运算符和分隔符
++
,--
,)
,]
或}
To allow complex statements to occupy a single line, a semicolon may be omitted before a closing "
)
" or "}
".以允许复杂语句以占据一行,分号可以关闭“之前被省略
)
”或“}
”。
This means that your code was equivalent to: 这意味着您的代码等同于:
if pr != nil;
{
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.