3 ms·
I totally agree. I love Swift's guard let. It makes early returning [1] easy: guard let value = optvalue else { return // optvalue is none } T
by gardaani 6y ago
I totally agree. I love Swift's guard let. It makes early returning [1] easy:
guard let value = optvalue else {
return // optvalue is none
}
There has been several proposals [2][3] to fix it in Rust but they don't seem to go anywhere.
I'm using this in my own code now to unwrap or return (it looks stupid):
let value = if let Some(value) = optvalue {
value
} else { // optvalue is none
return;
};
[1] https://szymonkrajewski.pl/why-should-you-return-early/ https://szymonkrajewski.pl/why-should-you-return-early/
[2] https://github.com/rust-lang/rfcs/issues/2616 https://github.com/rust-lang/rfcs/issues/2616
[3] https://github.com/rust-lang/rfcs/pull/1303 https://github.com/rust-lang/rfcs/pull/1303
- danappelxx 6y agoI missed `guard let` for a while too, but eventually stumbled upon this pattern which is almost as good: let value = match value { None => return, Some(value) => value };
- papaf 6y agoI use match as an inside out 'if let' but in this particular case I prefer to: let value = value.ok_or(MyError)?;