Which Go collections know their length, and which need it to be
evaluated (when using len)? In particular, do Go static arrays know
their length, or are they like C's?
Also, why does len return an int (I would expect uint)? I tried several
times to use unsigned ints for what they fit well (cardinals, ordinals)
but was blocked because of that, forced to use an int. Knowing that, why
have unsigned types at all? (It is certainly exceptional that the
additional bit makes a difference.)
Denis
the length of a Go array is part of its type and therefore known to
the compiler.
the length of a Go *slice* is part of the slice value.
> Also, why does len return an int (I would expect uint)? I tried several
> times to use unsigned ints for what they fit well (cardinals, ordinals) but
> was blocked because of that, forced to use an int. Knowing that, why have
> unsigned types at all? (It is certainly exceptional that the additional bit
> makes a difference.)
returning an int means that you can do:
for i := 0; i < len(a) - 1; i++ {
}
without worrying that it'll cause a hard-to-find cpu-hogging
loop if a is empty.
actually, that loop wouldn't even be valid because the
default type of an integer constant is int, so you'd
have to write:
for i := uint(0); i < len(a) - 1; i++ {
}
which is similarly dangerous in addition to being more verbose.
Also, why does len return an int (I would expect uint)?
> Also, why does len return an int (I would expect uint)? I tried
> several times to use unsigned ints for what they fit well (cardinals,
> ordinals) but was blocked because of that, forced to use an
> int. Knowing that, why have unsigned types at all? (It is certainly
> exceptional that the additional bit makes a difference.)
Unsigned types are not a good choice for counts, because they have odd
behaviour at 0, a common case. Signed types have odd behaviour at very
large and very small values, an uncommon case.
However, unsigned types are a good choice for collections of bitfields,
because you can shift them without worrying about what happens with the
sign bit. They are also a good choice for things like color values,
which range from 0 to 255 but are not counts. So while signed types are
far more common than unsigned types, unsigned types are still useful.
Ian
> Which Go collections know their length, and which need it to be evaluatedthe length of a Go array is part of its type and therefore known to
> (when using len)? In particular, do Go static arrays know their length, or
> are they like C's?
the compiler.
the length of a Go *slice* is part of the slice value.
(PS: did you note you replied to me only? Lists which reply-to field is
not set to the list, but to the original poster, constantly trap people.
I take the freedom to cc to the list.)