Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

errors3.rs has outdated informations #185

Closed
rusty-snake opened this issue Jul 1, 2019 · 3 comments
Closed

errors3.rs has outdated informations #185

rusty-snake opened this issue Jul 1, 2019 · 3 comments
Labels
A-exercises Area: Exercises C-bug Category: Bug

Comments

@rusty-snake
Copy link

// 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.
// Hence the error that you get if you run this code is:
// ```
// error[E0277]: the `?` operator can only be used in a function that returns `Result` (or another type that implements `std::ops::Try`)
// ```
// So we have to use another way of handling a `Result` within `main`.

Since rust 1.26 main can also return Result.

@komaeda komaeda added A-exercises Area: Exercises C-bug Category: Bug labels Jul 8, 2019
@mikemorris
Copy link

mikemorris commented Jul 13, 2019

I was just working through this exercise and noticed this too, the following is now a acceptable solution solution that compiles for example

fn main() -> Result<String, ParseIntError> {
    let mut tokens = 100;
    let pretend_user_input = "8";

    let cost = total_cost(pretend_user_input)?;

    if cost > tokens {
        Ok(format!("You can't afford that many!"))
    } else {
        tokens -= cost;
        Ok(format!("You now have {} tokens.", tokens))
    }
}

@rusty-snake
Copy link
Author

maybe better:fn main() -> Result<(), AnyErrorType>

because fn main() -> String isn't allowed.

pedantic79 pushed a commit to pedantic79/rustlings that referenced this issue Apr 11, 2020
@EvanCarroll
Copy link
Contributor

I'm not sure that this issue should be marked as completed. Previously the lesson was that you can use ? only if you're returning a result, but if you want to panic on error and only concern yourself with success you can use the .unwrap().

let cost = total_cost(pretend_user_input)?; # old
let cost = total_cost(pretend_user_input).unwrap(); #fixed

The hint says,

If other functions can return a `Result`, why shouldn't `main`?

That's pushing the users to make main return a Result. The user is likely to look up "how do I make main return a result".

ppp3 pushed a commit to ppp3/rustlings that referenced this issue May 23, 2022
dmoore04 pushed a commit to dmoore04/rustlings that referenced this issue Sep 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-exercises Area: Exercises C-bug Category: Bug
Projects
None yet
Development

No branches or pull requests

4 participants