go的内建函数len为什么返回int而不是uint?

// The len built-in function returns the length of v, according to its type:
//
//    Array: the number of elements in v.
//    Pointer to array: the number of elements in *v (even if v is nil).
//    Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
//    String: the number of bytes in v.
//    Channel: the number of elements queued (unread) in the channel buffer;
//             if v is nil, len(v) is zero.
//
// For some arguments, such as a string literal or a simple array expression, the
// result can be a constant. See the Go language specification's "Length and
// capacity" section for details.
func len(v Type) int

返回int是有什么其他的考量吗?

长度返回uint不是更合理吗?

阅读 1.9k
1 个回答

C++ stl 的设计里,长度就是 unsigned 。经过长年的实践,大家认为这是一个错误。

参考:Do not use unsigned for non-negativity; Subscripts and sizes should be signed

摘要一下:

  1. 无符号的运算与有符号数是不同的,他是模 2^n 的。比如 0-1 会得到一个很大的正数。这与通常数学规律不同,从而会影响程序员书写与理解代码,并且确实引起了很多程序 bug 。
  2. 无符号数并不能是程序更安全。-1 与 4294967295 会给程序带来同样的问题。
  3. 无符号数不能避免或减少任何程序中需要的范围检查、测试等工作。使用无符号数与有符号数,对程序员的工作量的没有影响。(使用无符号类型,还不如加一个注释说明这个数应该一直是非负的)
  4. (可能仅适用与 C/C++)有符号运算可以更好的优化。
  5. 混用有符号数与无符号数是程序变得复杂,不容易书写与理解。

估计基于类似的原因,go 选择了 int 。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题