读取的字节数和无符号数

huangapple go评论83阅读模式
英文:

The number of bytes read and unsigned numbers

问题

作为澄清我的问题的例子,在Google Go 1.0中,在"io"包中定义了以下接口:

type Reader interface {
    Read(p []byte) (n int, err error)
}

特别是结果参数列表(n int, err error)引起了我的兴趣。根据接口的文档,字节数不能为负数:

> 它返回读取的字节数(0 <= n <= len(p))[...]

在C语言中,使用int的原因是使用带有特殊值-1来表示错误条件(参见Effective Go: Multiple return values)。由于有多个返回值,不需要特殊的特殊值。

在Go 1.0中存在type uint

在只使用正数范围[0,∞)而不需要特殊的特殊值的情况下,为什么在这种情况下使用int而不是uint的具体原因是什么?

英文:

As an example to clarify my question, in Google Go 1.0, the following interface is defined in the "io" package:

type Reader interface {
    Read(p []byte) (n int, err error)
}

Especially the result parameter list (n int, err error) intrigues me. Intrinsically the number of bytes can not be negative, according to the documentation of the interface:

> It returns the number of bytes read (0 <= n <= len(p))[...]

In C the reason to use int was the in-band value -1 to signal an error condition (see Effective Go: Multiple return values). Because of multiple return values, special in-band values are not necessary.

There exists the type uint in Go 1.0.

What is the specific reason for using int versus uint in the case of values that only use the positive range [0,∞) without the need for having special in-band values?

答案1

得分: 5

整数的事实上的数值类型是int。这部分是因为有符号的int溢出以一种更明显的方式发生。
一个uint的小溢出看起来像一个有效的值,但是一个有符号的int的小溢出将是负数,并且在期望一个正整数的地方引发恐慌,例如切片。

这很重要,因为你通常会从Read()中获取'n',并将'p'切片到该长度。

例如:

n, err := a.Read(p)
p = p[:n]
processReadData(p)
英文:

The de facto numeric type for integers is int. This is partly because signed int overflow in a more obvious way.
A small overflow of an uint ends up looking like a valid value, but a small overflow of a signed int will be negative and panic in places expecting a positive integer, eg. slicing.

This is important because you'll commonly take the 'n' from Read() and slice 'p' to that length.

eg.

n, err := a.Read(p)
p = p[:n]
processReadData(p)

答案2

得分: 1

在大多数情况下,整数的事实上的数值类型是int。例如,len(x)cap(x)返回的是int值,即使它们也不能为负数。在大多数情况下,返回一个int值有助于避免不同数值类型之间的类型转换。

所以,是的,Read()可以返回一个uint,但这会使它稍微更难处理。

英文:

The de facto numeric type for integers in most cases is int. For example, len(x) and cap(x) return int values even though those too cannot be negative. In most cases returning an int helps avoid type conversions between different numeric types.

So yes, Read() could have returned a uint, but this would make it slightly more unwieldy to work with.

huangapple
  • 本文由 发表于 2012年6月5日 07:48:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/10889880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定