Michael Pacheco
Michael Pacheco

Reputation: 1164

What is the difference between ref and & in Rust pattern matching

Doing this exercise https://github.com/rust-lang/rustlings/blob/main/exercises/option/option3.rs I discovered the ref keyword and I'm very confused when should I use & or ref in a pattern matching. In this example, every match outputs the same message, but I couldn't tell their differences:

struct Point { x: i32, y: i32}

fn main() {
    let y: Option<Point> = Some(Point { x: 100, y: 200 });

    match &y {
        Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y),
        _ => println!("no match"),
    }

    match y {
        Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
        _ => println!("no match"),
    }

    match &y {
        Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y),
        _ => println!("no match"),
    }

    y;
}

Upvotes: 7

Views: 1400

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70910

ref is older. The fact the matching against a reference gives a reference is a result of the match ergonomics feature.

They are not exactly the same, but generally you can choose. I and many other people prefer the & form, although I saw people that do not like match ergonomics and prefer the explicit ref always.

There are case where you cannot take a reference and then you're forced to use ref. I also prefer to use ref in cases like Option::as_ref() and Option::as_mut(), where with match ergonomics they will have exactly the same code and this is confusing in my opinion, while using ref one is just ref and the other uses ref mut.

Upvotes: 5

Related Questions