Start learning free

LESSON 63 OF 348 · STRINGS I

Exceeding String Bounds in Rust in Rust

Lesson

When accessing string characters with indices, the most common problem we can run into is exceeding the string's bounds.

Remember, the characters of a string are normally indexed from 0 to length - 1.

Any index which is strictly greater than length - 1 is invalid.

When you try to access a character with an invalid index, Rust panics at runtime:

let car = "ford";

// Valid indices: 0, 1, 2, 3
println!("{}", car.chars().nth(0).unwrap()); // Output: f
println!("{}", car.chars().nth(3).unwrap()); // Output: d

// Invalid indices: 4, 30
println!("{}", car.chars().nth(4).unwrap()); // panics: called `Option::unwrap()` on a `None` value
println!("{}", car.chars().nth(30).unwrap()); // panics: called `Option::unwrap()` on a `None` value

Like Python, Rust panics when you access an out-of-bounds index, which is actually a good thing. Being told about a mistake early on is much better than silently getting wrong data and running into problems later.

In conclusion, we always want to double check our code to make sure that we don't exceed one string's bounds in our programs.


Assignment
Follow the Coding Tutorial and let's practice with string bounds!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Exceeding String Bounds in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free