Array size in rust language

while creating array in rust

const array_size:u8 = 20;
fn main()
{
    let array:[u8;array_size];
}   

it print out error that array size must be usize
array size must be unsigned integer ok. why it is not supporting u8,u32 ..

  1. is it because to avoid any type of errors by the complier.
  2. or make the complier design simple.
  3. or due to any other reason or any thing related to hardware architect.

can any one explain the reason ?

In Rust, you can't convert between types implicitely. Your array_size variable is of type u8, but the array's length must be usize. You can do array_size as usize to cast it, or you can declare array_size as usize.

The compiler could support this, sure. It's a choice that was made when designing the language, and is for the same reason that you can't index into an array with anything but an usize. Rust doesn't really buy into automatic conversion between any integer types.

2 Likes

Which I found to be really annoying.

Often one wants to index an array with something that is a value in it's own right, not just a array index.

A simple, contrived, example might be a lookup table that converts Centigrade to Fahrenheit. In which case the index is a value in Centigrade and may only be 8 or 16 bits. To do the look up requires a type conversion.

On reflection though I'm happy with the Rust approach.

We don't want implicit type conversions going on and get into a mess like you can in C.

An alternative might be having two types for arrays, a type for the elements and a type for the indices. As is done in Ada if I remember correctly. That has it's own down sides.

Like others, at first I found the need for array indexing in Rust to use usize to be inconvenient. However, that decision aligns with Rust's avoidance of hidden code cost, since at the hardware level arrays are indexed by usize registers so that they can span arbitrary amounts of memory.

For some RISC architectures Rust's choice of usize leads to faster and/or more compact code than would use of non-usize index widths. Thus I now appreciate Rust's gentle push toward code efficiency.

6 Likes

if i understand the platform support list correctly, there is at least one 16bit platform (msp430-none-elf) currently supported by rust. wouldn't using a u32 as an index be impossible there?

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.