Why did Go creators choose to not treat nil
as false
? What why did they think it is better to explicitly compare values to nil
? Is there a reliable source that would explain why is that is Go? What was their opinion? What was the logic behind this decision?
I'm looking for a historical reference.
E.g.:
f, err := os.Open(name)
if err != nil {
return err
}
Than to implicitly cast nil
s to false
like in many other languages:
f, err := os.Open(name)
if err {
return err
}
As of now, the latter would give:
non-bool err (type error) used as if condition
Some languages did that and it caused too many problems. It's primarily a violation of principle of least surprise. Some of the problems are:
true
. A pointer to false
boolean value would evaluate to true
. All of that would create new and larger set of complications, aka more bugs.nil
would be valid. Comparing a boolean to nil
would be valid. That creates a semantic confusion. More bugs.if a == '3' && b { .. }
kind of cases where you forget to add the comparison so b
always evaluates to true
even if it's not what you intend. More and more bugs.Go people probably thought about it and preferred code with less bugs is better.
There could be a shortcut though just to propagate the error to the caller such as:
require f := os.Open(name)
// if the call returns error, return error
EDIT: I'm happy to report that Go team adopted a very similar approach to what I suggested, in Go 2. Only they used the keyword check
instead:
check f := os.Open(name)
// if the call returns error run the declared error handler
// which in turn, can return the error or do something else about it.
While I can't find an exact reason in any of the golang documentation or developer discussions, the closest reason is simply that that absence of a value (nil) should not be interpreted as false. This is also in line with the fact that golang is a very opinionated language, and that its authors felt that not casting types when evaluating for true/false would lead to better quality of code.