英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论