1
0
Fork 0
mirror of https://github.com/rust-lang/rustlings.git synced 2024-06-07 09:46:12 +02:00
rustlings/exercises/error_handling/errors3.rs

63 lines
1.4 KiB
Rust
Raw Normal View History

2018-02-22 07:09:53 +01:00
// errors3.rs
2016-06-21 16:40:32 +02:00
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though--
2018-11-09 20:31:14 +01:00
// we can't use the `?` operator in the `main()` function! Why not?
2016-06-21 16:40:32 +02:00
// What should we do instead? Scroll for hints!
use std::num::ParseIntError;
fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
2018-11-09 20:31:14 +01:00
let cost = total_cost(pretend_user_input)?;
2016-06-21 16:40:32 +02:00
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
2018-11-09 20:31:14 +01:00
let qty = item_quantity.parse::<i32>()?;
2016-06-21 16:40:32 +02:00
Ok(qty * cost_per_item + processing_fee)
}
2018-11-09 20:31:14 +01:00
// Since the `?` operator returns an `Err` early if the thing it's trying to
// do fails, you can only use the `?` operator in functions that have a
2016-06-21 16:40:32 +02:00
// `Result` as their return type.
2018-11-09 20:31:14 +01:00
// Hence the error that you get if you run this code is:
2016-06-21 16:40:32 +02:00
// ```
2018-11-09 20:31:14 +01:00
// error[E0277]: the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
2016-06-21 16:40:32 +02:00
// ```
2018-11-09 20:31:14 +01:00
// So we have to use another way of handling a `Result` within `main`.
2016-06-21 16:40:32 +02:00
// Decide what we should do if `pretend_user_input` has a string value that does
2018-11-09 20:31:14 +01:00
// not parse to an integer, and implement that instead of using the `?`
// operator.