You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I call both function in a row, and store both error into the same variable of type error.
// new variable "err"err:=A()
// reuse previous variable "err"err=B()
After each call, log err value, and log a custom message if any error is returned:
err:=A()
fmt.Printf("a value is '%v'\n", err)
iferr==nil {
fmt.Println("a is nil")
} else {
fmt.Println("a is not nil")
}
err=B()
fmt.Printf("b value is '%v'\n", err)
iferr==nil {
fmt.Println("b is nil")
} else {
fmt.Println("b is not nil")
}
What did you expect to see?
Both function return nil, so we should have the following:
a value is '<nil>'
a is nil
b value is '<nil>'
b is nil
What did you see instead?
a value is '<nil>'
a is nil
b value is '<nil>'
b is not nil
It says b value is '<nil>', but the condition if err == nil is still evaluated to true.
Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.
I considered this a bug from an user/developer point of view, as this is an unexpected behavior, that's why I did not ask a question on other tools. I search on Github issue list but did not find anything either.
With your explanations, I now understand what's going on under the hood.
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes (using "Go dev branch" from Go playground)
What operating system and processor architecture are you using (
go env
)?Unknown (Go Playground handle this for me)
What did you do?
I have a
CustomError
struct with an error:I have 2 functions, one returning a builtin error (if any), and one other returning a
CustomError
(if any).I call both function in a row, and store both error into the same variable of type
error
.After each call, log
err
value, and log a custom message if any error is returned:What did you expect to see?
Both function return
nil
, so we should have the following:What did you see instead?
It says
b value is '<nil>'
, but the conditionif err == nil
is still evaluated totrue
.Whole code to reproduce the issue is available below and in this Go playground example too:
One interesting thing is when I change A function to return
*CustomError
too, instead of builtinerror
:In this case, I get the expected behavior (everything is nil):
Here is the updated code for this working case, as long with the new Go Playground example:
The text was updated successfully, but these errors were encountered: