gpt4 book ai didi

go - 为什么这不检查 nil in go 工作?

转载 作者:IT王子 更新时间:2023-10-29 02:26:36 27 4
gpt4 key购买 nike

在第一个代码示例中,“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)
}
}

如果我注释掉 nil 检查 if 语句,它编译正常:

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

起初我倾向于认为这是代码前面的一些语法错误,但当我注释掉这些行时它起作用的事实让我认为这是另外一回事。

emailToPerson 是 map[string]*Person 类型,其中 Person 是一个结构体

提前致谢。如果事实证明这是非常简单的事情,我们深表歉意。

最佳答案

左大括号需要与 if 在同一行:

if pr != nil { 

来自Go spec on semicolons :

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:

  1. 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, or return
    • one of the operators and delimiters ++, --, ), ], or }
  2. To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ")" or "}".

这意味着您的代码等同于:

if pr != nil;
{
// ...
}

关于go - 为什么这不检查 nil in go 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32702338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com