Is there a guide that covers `ref` and `ref mut`?


#1

Is there a guide that covers ref and ref mut?

I can’t find them in the book.


#2

ref and ref mut are part of patterns

Thanks for raising this, maybe that’s a common confusion. /cc @steveklabnik


#3

They are very confusing. Especially since they come up when I’m trying to borrow fields from nested structs.


#4

But it was in the context of a match, was it? So “patterns” is the right place to put it, but maybe a hint in the references section, that the information can be found otherwise would be helpful.


#5

My intuition when dealing with borrow shenanigans is to refer to the borrowing section of the book. I didn’t think of pattern matching.

I would love to see examples of mutably borrowing from nested structs in the guide (maybe Option<Result<SomeStruct>>).


#6

I have a hard time understanding what your specific problem was. Can you post a minimal example of what was failing?


#7

I don’t have a code example right now.

My main issue with ref and ref mut when applied to nested data is that I don’t understand how they interact with the lifetime, ownership, and mutability of the parent data.

I’ll post a better example when I get home.


#8

While trying to come up with a code example demonstrating my confusion on how ref and ref mut work I think I got it. So, problem solved ??? ¯\_(ツ)_/¯

The way I understand it is that ref and ref mut are needed because in a match pattern "&" deconstructs references, so we need a way to construct references to captured variables. Did I get this right?


#9

Yes, that’s exactly what ref and ref mut are for.
Perhaps the Appendix of the second edition should link to the chapters that cover the concepts?