Search code examples
rust

Why doesn't this reference pattern dereference and then borrow before matching?


There is some introduction of the reference patterns in The Rust Reference and it says

Reference patterns dereference the pointers that are being matched and, thus, borrow them

So I try to write some codes to get a feel:

 struct Myss<'a> {
    inner: &'a str,
}

impl<'a> Myss<'a> {
    fn new(s: &'a str) -> Self {
        Myss { inner: s }
    }
}

impl<'a> Deref for Myss<'a> {
    type Target = &'a str;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}
fn main() {
    let s = "abcde";
    let mss = Myss::new("abcde");
    
    match &mss { // why not same as  & (*(&mss)) -> &(* mss.deref()) -> & (&str) -> &&str
        &"abcde" => { // => Errors here: expected `Myss<'_>`, found `&str`
            println!("matched");
        }
        _ => {
            println!("others");
        }
    }
}

The ms variable owns a type &Myss which is a reference to the type which has the Deref trait implemented and the pattern &"abcde" imo is a reference pattern. I expect the value will follow a path like

`& (*(&mss)) -> &(* mss.deref()) -> & (* &Target) -> & Target -> & (&str) since the reference has said the pointers will be firstly dereferenced and then borrowed(or am i missing something?)

which can been matched against the pattern &"abcde" with type & (&str).

But the compiler complains that

Mismatched types
expected `Myss<'_>`, found `&str`

Why the reference is not firstly been dereferenced and then borrowed as the reference has introduced?

(The compiler version: rustc 1.77.2)


Solution

  • I don't know what The Reference means by "and, thus, borrow them", reference patterns don't borrow anything, they only dereference.

    However, they don't call Deref, which is why your code doesn't work. Deref in patterns is the subject of work-in-progress deref patterns, which are not fully implemented yet alone stabilized.