Rust’s expect method extracts a value from an Option or Result. When the value is absent or represents failure, expect panics with the message you provide. section 6.3
Adding a useful failure message
Calling input.get(3).unwrap() on a three-item vector produces the vague message “called Option::unwrap() on a None value.” Replacing it with input.get(3).expect("Input vector needs at least 4 items") reports the actual requirement and the source location. section 6.3
expect is clearer than unwrap because its message documents what the code assumes and helps identify which operation failed. It still panics, so it is useful while writing code or when failure should be impossible, but finished programs should usually use non-panicking handling when customers may encounter the problem. section 6.3
Use expect when:
- A missing value indicates a violated assumption that should stop the program. section 6.3
- A custom message can explain the required condition more clearly than unwrap. section 6.3
fn get_fourth(input: &Vec<i32>) -> i32 {
let fourth = input.get(3).expect("Input vector needs at least 4 items");
*fourth
}
fn main() {
let my_vec = vec![9, 0, 10];
let fourth = get_fourth(&my_vec);
}
Compare the expect call with its resulting panic message in b16. section 6.3

