Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q6: cargo build error: index out of bounds when use a[10], but success when use a[index] #7

Open
yangwenmai opened this issue Apr 23, 2019 · 0 comments
Labels
question Further information is requested

Comments

@yangwenmai
Copy link
Owner

yangwenmai commented Apr 23, 2019

思考?

// 可以正确编译: cargo build
    let index = 10;
    let element = a[index];
    println!("The value of element is: {}", element);
    // 编译报错:cargo build
    println!("a[0] is: {}, a[6] is: {}", a[0], a[6]);// error: index out of bounds: the len is 5 but the index is 6
    let element = a[10];
    println!("The value of element is: {}", element);

为什么声明了一个变量值,然后通过这个变量值去取超过数组的索引时,不会报错。而直接使用常量值或明确的值时,会编译报错?

常量值的类型必须是 usize,否则报错: | ^^^^^^^^ slice indices are of typeusizeor ranges ofusize``

这个应该是跟编译器有关。

@yangwenmai yangwenmai added the question Further information is requested label Apr 23, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant