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:
- All non-nil values would evaluate to
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.
- Assigning a boolean to
nil
would be valid. Comparing a boolean to nil
would be valid. That creates a semantic confusion. More bugs.
- Code would be harder to read because it hides the intent. It's impossible to tell from an expression if you want to check a boolean's value or assert "non-nilness" of some other type of variable. More bugs.
- Omitted operands in comparison operations in expressions would compile fine, making identifying bugs harder. Think about
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.
type Err bool
and thenfunc (e Err) Error() { "Im an error" }
. In that case, false is actually an error. Obviously, it's unlikely anyone writes that code. But languages with a truthiness concept implicitly impose some standard meanings behind non-boolean data (0/1 being false/true for example). The Go authors chose to be explicit rather than implicit here probably due to it simplifying the language as well as not wanting surprises in general – David Budworth Apr 26 '16 at 5:09