Skip to content

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

Open
@yangwenmai

Description

@yangwenmai

思考?

// 可以正确编译: 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``

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions