IF语句下面的代码从未执行。

huangapple go评论73阅读模式
英文:

Code below IF statement is never executed

问题

有一部分代码的行为出现了意外情况。

. . .
fmt.Println("Error:", err)
if err == nil {
    return err
}
fmt.Println("Done category")
. . .

上述代码段的输出结果如下:

Error: <nil>

如果我移除 if 语句,代码的行为就符合预期。

参考链接:https://github.com/skarllot/flogviewer/blob/master/wlog/parser.go#L138

英文:

There's a section of my code that has unexpected behaviour.

. . .
fmt.Println(&quot;Error:&quot;, err)
if err == nil {
	return err
}
fmt.Println(&quot;Done category&quot;)
. . .

The section above has the following output

Error: &lt;nil&gt;

The code below if statement is never executed. If I remove the if statement the code behaves as expected.

Reference: https://github.com/skarllot/flogviewer/blob/master/wlog/parser.go#L138

答案1

得分: 3

让我们逐步进行。

fmt.Println("Error:", err)

如果输出是Error: <nil>,那么你的err变量是nil

if err == nil {
    return err
}

这段代码的意思是,"如果err变量是nil(我们已经确定它是),则返回nil值。

在这一点上,你的函数已经返回了,所以下面的代码将不会执行。

也许你的意思是这一行代码?:

if err != nil {
//     ^^ 不等于?
英文:

Let's step through it.

fmt.Println(&quot;Error:&quot;, err)

If the output is Error: &lt;nil&gt; .. then your err variable is nil.

if err == nil {
    return err
}

This is saying .. "if the err variable is nil (which it is .. we established that above) ... then return the nil value.

At this point .. your function has returned.. so nothing else below it will run.

Perhaps you meant this line instead?:

if err != nil {
//     ^^ NOT equal?

huangapple
  • 本文由 发表于 2015年3月10日 05:58:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/28952513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定