14

In more practical terms: What integer data type should I use for indices in a vector, length of arrays, etc?

There are lots of discussions on this topic for pre-1.0 Rust floating around on the internet and I can't find an authoritative answer on the final decision.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Perseids
  • 12,584
  • 5
  • 40
  • 64

1 Answers1

18

That would be usize and isize (pointer-size types, unsigned and signed). The reference says that the maximal size of an array is the maximum value of isize such that differences of positions can be calculated.

The functions of std::Vec use usize for all indices, though.

filmor
  • 30,840
  • 6
  • 50
  • 48
  • 2
    Note that on a 32 bits system, `isize` is limited to 32 bits, so this actually constrains the size of an array to 2GB even though 4GB are available. On 64 bits, I doubt it'll be an issue. – Matthieu M. Aug 31 '15 at 11:39
  • 2
    @MatthieuM.: on existing 64-bit platforms addresses are only 48 bits, so 63 bits is ample. – Chris Morgan Aug 31 '15 at 12:08
  • 3
    @MatthieuM. why is it 2GB and not 2G elements? – Janus Troelsen Sep 01 '15 at 00:46
  • @JanusTroelsen It is 2G elements, which can be as little as 2GB (even though you’d have enough address space for more) when elements are byte-sized. – Simon Sapin Sep 01 '15 at 04:41
  • 1
    @JanusTroelsen: I supposed, Rust having low-level capabilities, that one should always be able to compute the difference between a pointer to the first element and a pointer one-past-the-end element, even when casting those pointers to `*const u8`. Well, [let's ask](http://stackoverflow.com/questions/32324794/maximum-size-of-an-array-in-32-bits)! – Matthieu M. Sep 01 '15 at 06:20
  • This link has been removed. – Pedro Paulo Amorim Sep 19 '19 at 16:43
  • Thanks for the info, I fixed the link now. – filmor Sep 20 '19 at 06:57