Panics
A panic stops the program right away and prints a message. Rust uses panics for problems that should never happen.
panic!
Call panic! with a message to stop the program on purpose.
let age = -1;if age < 0 { panic!("age can't be negative");}The message can use {} like println!. Code after a panic never runs.
unwrap and expect
unwrap() takes the value out of a Some. On None, it panics. expect("msg") does the same, but panics with your message. The same two methods also work on Result, which you meet in the next unit.
let x: Option<i32> = Some(4);println!("{}", x.unwrap()); // 4let y: Option<i32> = None;// y.expect("need y"); // panicsIndex panics and get
v[i] panics if i is past the end. The compiler can't check this for a Vec, so it only fails at run time. v.get(i) never panics: it returns Some(&value) or None.
let v = vec![10, 20, 30];println!("{:?}", v.get(1)); // Some(20)println!("{:?}", v.get(9)); // NoneWhen to panic
- Panic for bugs: something your own code promised can't happen.
- Return a
Resultfor normal failures the caller can handle, like bad user input or a missing file. unwrapis fine in tests and quick examples.- In real code, prefer
expectwith a clear message when you are sure a value is there.
Remember
- A panic stops the program; nothing after it runs.
unwrapandexpectpanic onNone.v[i]can panic;v.get(i)gives anOption.- Panic for bugs, return errors for things that can go wrong.