Fix error_handling examples to use the ? operator

This commit is contained in:
Hynek Schlawack
2018-03-06 15:57:41 +01:00
parent 65bedf2d90
commit 3182b4d9ec
4 changed files with 21 additions and 26 deletions

View File

@@ -1,7 +1,7 @@
// errors3.rs
// 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--
// we can't call the `try!` macro in the `main()` function! Why not?
// we can't use the `?` operator in the `main()` function! Why not?
// What should we do instead? Scroll for hints!
use std::num::ParseIntError;
@@ -10,7 +10,7 @@ fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = try!(total_cost(pretend_user_input));
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
@@ -23,7 +23,7 @@ fn main() {
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = try!(item_quantity.parse::<i32>());
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
@@ -45,23 +45,18 @@ pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
// Since the `try!` macro returns an `Err` early if the thing it's trying to
// do fails, you can only use the `try!` macro in functions that have a
// 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
// `Result` as their return type.
// The error that you get if you run this code is:
// Hence the error that you get if you run this code is:
// ```
// error: mismatched types:
// expected `()`,
// found `std::result::Result<_, _>`
// error[E0277]: the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
// ```
// which is saying that the expected return type of the `main` function is
// the empty tuple, but we tried to return a `Result`-- and that's happening
// in the implementation of `try!`. The `main` function never has a return type,
// so we have to use another way of handling a `Result` within `main`.
// So we have to use another way of handling a `Result` within `main`.
// Decide what we should do if `pretend_user_input` has a string value that does
// not parse to an integer, and implement that instead of calling the `try!`
// macro.
// not parse to an integer, and implement that instead of using the `?`
// operator.