Number of read bytes and unsigned numbers

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 changes the list of parameters (n int, err error) . In fact, the number of bytes cannot be negative, according to the interface documentation:

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

In C, the reason for using int was an in-band value of -1 to signal an error (see Effective Transition: Multiple Return Values ). Due to the many return values, special in-band values ​​are not needed.

There is a type uint in Go 1.0.

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

+4
source share
2 answers

The actual numeric type for integers in most cases is int . For example, len(x) and cap(x) return int values, even if they cannot be negative either. In most cases, returning int helps to avoid type conversion between different numeric types.

So yes, Read() could return uint , but that would make it a little more cumbersome to work with.

+1
source

The actual numeric type for integers is int. This is partly because a signed int overflow is more obvious. A small overflow of uint ultimately looks like a valid value, but a small overflow of a signed int will be negative and panic in places expecting a positive integer, for example. cutting.

This is important because you usually take 'n' from Read () and slice 'p' to this length.

eg.

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

Source: https://habr.com/ru/post/1416072/


All Articles