The index versus the position in an array

So, the first index in a Rus array is notated as index 0. VBA has a feature where one can begin and end the array at a position other than 0 thus:

Dim some_array(1 To 4) As String

Does Rust have a similar functionality, or must all arrays begin with the 0 index?

You could create your own newtype (wrapper type around arrays or Vec or slices or whatever) that indexes with an offset.

3 Likes

no, all Rust built-in array-like types start their indexing at 0. custom types can override indexing to do what they want though, e.g. HashMap overrides it to work with arbitrary key types.

1 Like

For indexing by integers, anything other than starting from zero is a mis-feature: E.W. Dijkstra Archive: Why numbering should start at zero (EWD 831)

However, if you want to index by your own custom type (not an integer) then you can do that by implementing ops::Index<YourType>: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=abc925ea382411ebbcd4f57f1fa15953

You might want to do this to allow moves[Piece::Queen], for example.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.