What is the correct type to use for an array index?

前端 未结 1 1435
执念已碎
执念已碎 2021-01-11 16:39

This code works, but I want to explicitly declare the type of the index range max. However uX or iX, where X = 8, 16 or 32 gives compi

相关标签:
1条回答
  • 2021-01-11 17:43

    The compiler gives you a note about this:

       = note: slice indices are of type `usize`
    

    You must index a slice with a usize. usize is an unsigned integral type that has the same size as a pointer, and can represent a memory offset or the size of an object in memory. On 32-bit systems, it's a 32-bit integer, and on 64-bit systems, it's a 64-bit integer. Declare your index variables as usize unless you really have a lot of them, in which case you can use x as usize to cast them to an usize.

    When you leave out the type annotation, Rust deduces that your integer literals must be of type usize because slices implement Index<usize> and not Index<i32> or Index<any other integral type>.

    0 讨论(0)
提交回复
热议问题