Do you only use it if you want to output/use the content from in an Option type with some kind of error-handling?
fn main() {
let x : Option<String> = Some("lol".to_string());
let y : Option<String> = Some("lol".to_string());
let z : Option<String> = Some("lol".to_string());
//So this...
match x {
Some(a) => {
println!("{}", a);
},
_ => {}
}
//Is exactly the same as this:
if let Some(a) = y {
println!("{}", a);
}
//But why wouldn't you just do this?:
println!("{}", z.unwrap());
}
Would be cool if someone was able to explain this phenomenon noob-friendly with a few examples.
Thanks!
What do you think that should do when z is None? Evaluation order dictates that the println!() call must have its arguments ready by the time it is unconditionally executed. And unwrap() also unconditionally returns an inner value – it has to panic if the Option is None.
It seems to me you have a fundamental misunderstanding on expression evaluation – in particular, it's not magic, the compiler can't guess your intention, and more importantly, even if it tried to, it shouldn't actively alter the control flow just so that your function calls don't panic.