How do I use a paremeter to index an array in rust? [duplicate]

你。 提交于 2021-02-05 12:31:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!