2018-02-22 13:09:53 +07:00
|
|
|
// option1.rs
|
2016-02-11 06:37:26 +06:00
|
|
|
// This example panics because the second time it calls `pop`, the `vec`
|
|
|
|
// is empty, so `pop` returns `None`, and `unwrap` panics if it's called
|
|
|
|
// on `None`. Handle this in a more graceful way than calling `unwrap`!
|
|
|
|
// Scroll down for hints :)
|
|
|
|
|
2019-07-27 06:44:10 +07:00
|
|
|
pub fn pop_too_much() -> bool {
|
2016-02-11 06:37:26 +06:00
|
|
|
let mut list = vec![3];
|
|
|
|
|
|
|
|
let last = list.pop().unwrap();
|
|
|
|
println!("The last item in the list is {:?}", last);
|
|
|
|
|
|
|
|
let second_to_last = list.pop().unwrap();
|
2019-05-22 18:48:32 +07:00
|
|
|
println!(
|
|
|
|
"The second-to-last item in the list is {:?}",
|
|
|
|
second_to_last
|
|
|
|
);
|
2019-07-27 06:44:10 +07:00
|
|
|
true
|
2016-02-11 06:37:26 +06:00
|
|
|
}
|
|
|
|
|
2019-07-27 06:44:10 +07:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2016-02-11 06:37:26 +06:00
|
|
|
|
2019-07-27 06:44:10 +07:00
|
|
|
#[test]
|
|
|
|
fn should_not_panic() {
|
2019-10-26 04:27:24 +07:00
|
|
|
assert!(pop_too_much());
|
2019-07-27 06:44:10 +07:00
|
|
|
}
|
|
|
|
}
|
2016-02-11 06:37:26 +06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Try using a `match` statement where the arms are `Some(thing)` and `None`.
|
|
|
|
// Or set a default value to print out if you get `None` by using the
|
|
|
|
// function `unwrap_or`.
|
|
|
|
// Or use an `if let` statement on the result of `pop()` to both destructure
|
|
|
|
// a `Some` value and only print out something if we have a value!
|