Discussing Reference Patterns

⚓ rust    📅 2025-06-08    👤 surdeus    👁️ 2      

surdeus

For the most part the docs are really well written and I don't get confused. But I did in this case. So I hope to discuss it a bit with others.

Reference Pattern: Definition

In the docs we find:

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

It was hard to read for me. My understanding goes something like:

Reference patterns test that the scrutinee is a reference, and either match its value, or bind it. When binding it, the value is reborrowed, not moved or copied.

PS2: even here, one needs clear examples to easily get it imho.

Reference Pattern: An Example

let b = match int_reference { &0 => "zero", _ => "some" };

If int_reference is a reference i.e & and its value is 0 we get the first arm. Changing 0 by hello it binds it to hello.

But mutable references it will need a reborrow, or they are moved. So when binding it needs to do hello = & *int_reference.

Assuming this is the case, I suspect the explanation is a bit too abridged in the documentation. That's why I added:

When binding it, the value is reborrowed, not moved or copied.

Reference Patterns: Are they Irrefutable ?

Docs say:

Reference patterns are always irrefutable.

But that example from the docs above clearly shows they are refutable! They wouldn't be if we had &x, where a bind happens; but that's not always true.

What's your interpretation?


PS: forgot adding the link, here it is Patterns - The Rust Reference

8 posts - 2 participants

Read full topic

🏷️ rust_feed