6 ms·
Rust noob here but couldn't you write if let Some(element) = some_vec.first() { println!("{}", element); // .. more code } and avoid the unwrap a
by ob 4y ago
Rust noob here but couldn't you write
if let Some(element) = some_vec.first() {
println!("{}", element);
// .. more code
}
and avoid the unwrap and the empty check?
Edit: Added a `let` I had forgotten.
- kccqzy 4y agoExactly (well other than "if let" here.) Every time you have a Boolean if condition with an unwrap, it means you are not taking advantage of the type system.
- ob 4y agoThanks, added.
- muglug 4y agoYes, but IMO that makes the code a bit more abstract: You've left behind an explicit "is this collection non-empty" and you're instead relying on a property of a non-empty collection. The PHP version can also be written as if (($element = reset($some_arr)) !== null) { echo $element; } But that code is similarly divorced from the imaginary pseudocode equivalent
- kccqzy 4y agoA collection is non-empty if and only if it has a first element. Therefore checking for non-emptiness is the same as checking for the existence of a first element.
- saghm 4y ago> Yes, but IMO that makes the code a bit more abstract: > You've left behind an explicit "is this collection non-empty" and you're instead relying on a property of a non-empty collection. More abstract for who? I think virtually all Rust programmers would easily understand the `if let` snippet, virtually all PHP programmers would understand the PHP snippet, and virtually all programmers of any language would understand that a non-empty array has a first element. I'm not at all convinced that most programmers would correctly guess that a function called `reset` is used to access the first element in an array though.