Match question Ok value


#1

Hello, I recently started learning Rust and so far I love it. I cant really understand what is going on over the “Guessing game” example on the Getting started tutorial.

let secret_number = rand::thread_rng().gen_range(1, 101);

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,
 };

I understand that if I get an error I call continue. But I dont understand what is going on over the Ok case on the tutorial says we match on Ok(num), which sets the name num to the unwrapped Ok value (the integer), and then we return it on the right-hand side

So my guess is… Ok comeswith the u32 integer I am looking for and I call it num and then I am returning it so guess can take it?

Thanks


#2

Yes thats right. The ‘’‘guess.trim().parse()’’’ returns a Result. If the result is Ok (AKA Not an Error) It stores a value. The match statement says “if the result is Ok, take the value stored in Ok and return it”

Hopefully thats makes sense. If not I can clarify :grinning:


#3

So basically, the match keyword is being used to perform pattern matching on the type returned by the expression on it’s right. This value happens to be an Algebraic Data Type, aka an enum, so the value will be one of many possible outcomes. In this case, the type is a:

Result<u32, <u32 as FromStr>::Err>

The compiler knows that we are attempting to parse a u32 value because on the left hand side, the type was specified to be a u32. Looking at the definition of the Result enum, we know that there are two possible outcomes: a Result::Ok() or a Result::Error(), each with their respective values.

Now, if it was able to correctly parse the string as a u32 value, then the result will be an Ok(u32), aka a Result::Ok(u32). The first value in that signature above is the Okay value. The second value is the Error value. If it failed to read a u32 value, you’d get the corresponding Result::Err(error) value.

These values generally always come with Display and/or Debug implemented, so you can easily print them to find out what the error is.


#4

If it helps, the match statement in this case is semantically equal to the following:

let guess: Result<u32, <u32 as FromStr>::Err> = guess.trim().parse();
let guess: u32 = if guess.is_ok() {
    guess.unwrap()
} else {
    continue
};