douxian1923 2016-04-26 02:01
浏览 105
已采纳

关于Go创作者为何选择不将“ nil”视为“ false”的历史参考[关闭]

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 nils 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
  • 写回答

2条回答 默认 最新

  • douduan5073 2016-04-27 00:04
    关注

    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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么