Program crashes with "index out of bounds" error

I ran the following Rust program and it crashed:

thread '' panicked at 'index out of bounds: the len is 1 but the index is 100', ../src/libcollections/vec.rs:1106

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    println!("{}", args[100]);
}

Is there any mechanism in Rust to prevent this kind of "index out of bound" error during compilation time? In this case, I actually expect the above program will fail compilation, given that Rust is language with memory safety.

What's your own definition of "memory safety"?

I am a newbie to Rust. The more I think about it, the "index out of bound" error is actually correct. In C/C++, in many cases the program will not crash while it is reading outside the array boundary.

My expectation for Rust is however higher, given that Rust is such an awesome language. For example, if args[100] returns something like Result<T, E>, then compiler will force the proper handling of array accessing.

I think this is quite un-ergonomic. Rust has to wear various hats, one of them is functional, but it also has to allow typical (without Result) access to arrays. But also there is "get":

How is the compiler supposed to know at compile time how many arguments there are at runtime?

2 Likes

Yes, the "get" is what I looked for. Thanks. It is like Haskell's Maybe Monad:
https://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe

It doesn't mean I will use it, but am happy yo know that Rust is cool enough to have this:

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    match args.get(2) {
        Some(v) => println!("{}", v),
        None => println!("{}", "Out of bound")
    }
}