6 ms·
Where does the n and err values come from? fn double_number(number_str: &str) -> Result<i32, ParseIntError> { match number_str.parse::<i32>() {
by msie 11y ago
Where does the n and err values come from?
fn double_number(number_str: &str) -> Result<i32, ParseIntError> {
match number_str.parse::<i32>() {
Ok(n) => Ok(2 * n),
Err(err) => Err(err),
}
}
- maxbrunsfeld 11y agoFrom the left-hand side of the `=>` arrows in the `match` expression.
- msie 11y agoI know that. Where do they come from before that?
- steveklabnik 11y agomatch number_str.parse::<i32>() { This matches on the return value of parse, which is an Result<T>. It can have two values: Err(E), or Ok(T). Ok(n) => Ok(2 * n), This line matches an Ok(T), and binds the value of type T to n, which can then be used on the right hand side. Err(err) => Err(err), this line matches an Err(T), and binds the value of type T to err, which can be used on the right hand side. The right hand sides re-wrap these values into another Result.
- phaylon 11y agoNitpick: Result<T, E> instead of Result<T> assuming Result is std::result::Result.
- steveklabnik 11y agoAhh yes, thank you.
- msie 11y agoThanks!
- deleted 11y ago[deleted]
- Retra 11y agoThis is pattern matching. They are bound on the left side, and the compiler basically 'solves an equation' to figure out what they are. For instance, if you wrote 5 * a = 35 You know exactly what the value of `a` is because that value matches the given pattern. Here, you have an equation that looks like Ok(n) = number_str.parse::<i32>() So `n` is defined by the value of `number_str.parse::<i32>()`.
- iso8859-1 11y agoCheck out this section on patterns: https://doc.rust-lang.org/book/patterns.html https://doc.rust-lang.org/book/patterns.html