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

Rust panics if index out of bounds #28230

Closed
alexispurslane opened this issue Sep 4, 2015 · 2 comments
Closed

Rust panics if index out of bounds #28230

alexispurslane opened this issue Sep 4, 2015 · 2 comments

Comments

@alexispurslane
Copy link
Contributor

fn main () {
    let x = vec![1, 2, 3];
    println!("Got: {}", x[88]);
}

This code compiles just fine, but, when I run it, I get an ICE, or something similar:

thread '<main>' panicked at 'index out of bounds: the len is 3 but the index is 88', ../src/libcollections/vec.rs:1047

Note that this is the same problem as in #28217. Here are the lines it references:

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Index<usize> for Vec<T> {
    type Output = T;

    #[inline]
    fn index(&self, index: usize) -> &T {
        // NB built-in indexing via `&[T]`
        &(**self)[index]
    }
}

I'm not sure if this is intended behavior or not, but it seems odd.

@alexispurslane alexispurslane changed the title Rust panics if index out of bounds, not in a compile-time error. Rust panics if index out of bounds Sep 4, 2015
@jdm
Copy link
Contributor

jdm commented Sep 4, 2015

This is intended behaviour - the [x] form of indexing panics, because it cannot return a reference to an element that doesn't exist. .get(x) returns an Option<T>, so it doesn't panic. The panicking behaviour is documented at https://doc.rust-lang.org/nightly/reference.html#index-expressions .

@jdm jdm closed this as completed Sep 4, 2015
@shamiao
Copy link
Contributor

shamiao commented Mar 30, 2017

recent url of index expressions document:
(stable) https://doc.rust-lang.org/reference.html#index-expressions
(nightly) https://doc.rust-lang.org/nightly/reference/expressions.html#index-expressions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants