ecorrales
ecorrales

Reputation: 157

Why getting panic in Rust program with an expect

Beginner Rust fan - I am getting a panic for either one of these.
I expected it from the first part, but not the second.
What am I missing?

fn main() {

    //let age = "4a";
    //let age2: i32 = age.trim().parse().unwrap();
    //println!("{:?}", age2);

    let age = "4a";
    let age2: i32 = age.trim().parse().expect("What was this?");
    println!("{:?}", age2);
}

Upvotes: -1

Views: 1057

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71430

From expect()'s documentation:

Panics

Panics if the value is an Err, with a panic message including the passed message, and the content of the Err.

The only difference to unwrap() is the customized error message.

See also: When should we use unwrap vs expect in Rust.

Upvotes: 4

Related Questions