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条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划