mirror of https://github.com/rust-lang/rustlings
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.4 KiB
Rust
63 lines
1.4 KiB
Rust
7 years ago
|
// errors3.rs
|
||
8 years ago
|
// 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--
|
||
6 years ago
|
// we can't use the `?` operator in the `main()` function! Why not?
|
||
8 years ago
|
// What should we do instead? Scroll for hints!
|
||
|
|
||
|
use std::num::ParseIntError;
|
||
|
|
||
|
fn main() {
|
||
|
let mut tokens = 100;
|
||
|
let pretend_user_input = "8";
|
||
|
|
||
6 years ago
|
let cost = total_cost(pretend_user_input)?;
|
||
8 years ago
|
|
||
|
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;
|
||
6 years ago
|
let qty = item_quantity.parse::<i32>()?;
|
||
8 years ago
|
|
||
|
Ok(qty * cost_per_item + processing_fee)
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
6 years ago
|
// 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
|
||
8 years ago
|
// `Result` as their return type.
|
||
|
|
||
6 years ago
|
// Hence the error that you get if you run this code is:
|
||
8 years ago
|
|
||
|
// ```
|
||
6 years ago
|
// error[E0277]: the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
|
||
8 years ago
|
// ```
|
||
|
|
||
6 years ago
|
// So we have to use another way of handling a `Result` within `main`.
|
||
8 years ago
|
|
||
|
// Decide what we should do if `pretend_user_input` has a string value that does
|
||
6 years ago
|
// not parse to an integer, and implement that instead of using the `?`
|
||
|
// operator.
|