Matching against method

Hi all,

I have below code piece:

fn main() {
let o = Some(1535);
match o.ok_or("Nope")* {
Ok(nr) => { println!("Ok branch"); assert_eq!(nr, 1535) }
Err(_) => { println!("Err branch"); assert!(false) }
}
}

My question is:
how come it's possible to match Some instance against its method?
Thanks in advance

Please consider using three backticks to render your code as something more readable. Like below.

```
// Your code goes here
let a = 3;
```

Which will give you code with syntax highliting.

// Your code goes here
let a = 3;
1 Like

According to the docs, here Option in std::option - Rust

ok_or Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err).

So you are then matching on the Ok or error produced in o.

If Ok then the nr becomes the original value in the Some.

I'm not sure I follow. You are not matching anything "against a method". You are matching the return value of a method call (which is just like any other expression) against some patterns. There's nothing surprising in it.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.