A nice comment in a forum thread (extracted below, but also see the shorter more facetious version below that) about references and their lifetimes in structs. Here is a link to the full thread over on users.rust-lang.org

I feel like I needed to hear or read this, and I feel like this sort of clarification is not put front and centre enough in rust learning material (as others in the thread say too). “The Book” certainly doesn’t seem interested in clarifying perspectives like this.


The Comment

Other languages use term “reference” for storing things “by reference” or just referencing any object anywhere in general. It’s not like that in Rust.

What Rust calls “reference” is a much more specific thing, that is no so general-purpose. It has a narrower, restrictive usage. Rust references are more like read-only or write-exclusive locks. They make their target unmovable and immutable for entire duration of their existence. They can’t exist on their own, only as a counterpart of an owned value.

References in structs also make the whole struct itself temporary, and everything that touches that struct becomes temporary and tied to the scope of the borrowed value that started it.

If these restrictions (that cause you fight with the borrow checker) aren’t what you want to achieve, then you don’t want temporary references.

99% of the time when you need to store something “by reference”, Box (or Arc or String or PathBuf or Vec or some other owned type) is the right answer.

Note that &T and Box<T> have identical representation in memory — a pointer. They differ by ownership.

In Short

From here

You’re not allowed to use references in structs until you think Rust is easy. They’re the evil-hardmode of Rust that will ruin your day.

😉

Use Box or Arc to store things in structs “by reference”. Temporary borrows don’t do what you think they do.

  • @JayjaderM
    link
    English
    31 month ago

    You’re welcome!

    I strongly agree with the feeling that there is a hole in the current material. At the same time, given the glimpses I’ve had of the other chapters and their sections, I wonder if we “just” need to get through the rest of the book.

    The current state of The Book and our progress through it as a community specifically reminds me of being at school: the lessons build on each other, and it always takes a certain amount of material covered before you start to really make sense of things and “refactor”, almost, your prior understanding.