Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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 compile errors. What is the correct type?

fn main() {
    let mut arr2: [[f64; 3]; 3] = [[0.0; 3]; 3];
    let pi: f64 = 3.1415926535;

    let max = 3; // let max: i16 e.g. is wrong

    for ii in 0..max {
        for jj in 0..3 {
            let i = ii as f64;
            let j = jj as f64;
            arr2[ii][jj] = ((i + j) * pi * 41.0).sqrt().sin();
            println!("arr2[{}][{}] is {}", ii, jj, arr2[ii][jj]);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...