Can’t resist pointing out how you should actually write the function in a “real” scenario (but still not handling errors properly), in case anyone wants to know.
If the list is guaranteed to have exactly two elements:
Even better to use expect with a short message of what the assumption is: “the string should contain a comma” if it ever panics you’ll know exactly why.
I think the problem is that many introductory examples use unwrap, so many beginner programmers don’t get exposed to alternatives like unwrap_or and the likes.
Yeah, we onboarded some folks into a Rust project last year and a few months in, they were genuinely surprised when I told them that unwrapping is pretty bad. Granted, they probably did read about it at some point and just forgot, but that isn’t helped by lots of code using .unwrap() either.
The weird part of rust is replacing straight forward semicolons from other languages with the more verbose
.unwrap();
.Just kidding, don’t lecture me about it.
?
But then someone will have to deal with it somewhere, better just unwrap it under the carpet.
Exactly
expr
Me, every time I try searching a Rust question.
That’s easy. Just do:
fn is_second_num_positive() -> bool { let input = "123,-45"; let is_positive = input.split(',') .collect::<Vec<&str>>() .last() .unwrap() .parse::<i32>() .unwrap() .is_positive(); is_positive }
Can’t resist pointing out how you should actually write the function in a “real” scenario (but still not handling errors properly), in case anyone wants to know.
If the list is guaranteed to have exactly two elements:
fn is_second_num_positive_exact(input: &str) -> bool { let (_, n) = input.split_once(',').unwrap(); n.parse::<i32>().unwrap() > 0 }
If you want to test the last element:
fn is_last_num_positive(input: &str) -> bool { let n = input.split(',').next_back().unwrap(); n.parse::<i32>().unwrap() > 0 }
If you want to test the 2nd (1-indexed) element:
fn is_second_num_positive(input: &str) -> bool { let n = input.split(',').nth(1).unwrap(); n.parse::<i32>().unwrap() > 0 }
Even better to use
expect
with a short message of what the assumption is: “the string should contain a comma” if it ever panics you’ll know exactly why.Can still use
.is_positive()
, though…The amount of people on the internet seriously complaining that both Rust error handling sucks and that
.unwrap();
is too verbose is just staggering.I think the problem is that many introductory examples use
unwrap
, so many beginner programmers don’t get exposed to alternatives likeunwrap_or
and the likes.Yeah, we onboarded some folks into a Rust project last year and a few months in, they were genuinely surprised when I told them that unwrapping is pretty bad. Granted, they probably did read about it at some point and just forgot, but that isn’t helped by lots of code using
.unwrap()
either.