Return immutable reference, taking mutable reference to self

The pattern you're trying to use here (take &mut self and return a &T, then use self again while the &T is alive) feels kinda odd for Rust. You could work around it with something like the partial borrowing RFC, but I feel like that's adding more magic to the compiler when structuring the code differently would make things simpler and more robust in the long term.

To explain why the initial example doesn't compile I sometimes find it useful to convert a function signature into words.To me, it says something like "I want to exclusively borrow self, then return a shared/immutable reference which lives as long as the original exclusive borrow". When it's phrased that way, trying to use self again (let b = &s.j) while its returned reference (the a) is alive seems like it's going against the normal rules of borrowing.

I wouldn't say the borrowing system is immature because loads of people are already using Rust in production with great success, so perhaps we can solve your problem by simply rephrasing it? It sounds like you're trying to do an operation while making sure people don't skip an important setup step. If so, you may be able to make invalid states unrepresentable by returning some sort of proxy object or doing the setup as part of the constructor.

2 Likes