问题
I'm trying to create a function that will take a parameter and use it as an index for an array rust will not let me do this and because of this I'm hoping to find an alternative method to achieve the same results.
although I'm not a 100% I believe that rust is not letting me run the code because it believes that the parameter I'm using might go beyond the lens of the array and for this I tried using the get()
function:
array.get(foo).unwrap();
however this still doesn't fix my current error.
Sample code to reproduce error:
fn example(foo: u32) {
let mut array: [u32; 3] = [0,0,0];
array[foo] = 9;
}
fn main() {
example(1);
}
The program fails to run with the complier giving me the error
array[foo] = 9
^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
This is my first time writing a problem on stack overflow so if i messed the formatting somewhere, sorry.
回答1:
The Problem seems to be in your function, as foo is of type foo: u32
You can see here and in your compiler result, that array indices have to be of type usize
so you could cast it to usize
as
array[foo as usize] = 9
or change your function header as
fn example(foo: usize) {
来源:https://stackoverflow.com/questions/56517606/how-do-i-use-a-paremeter-to-index-an-array-in-rust