An invariant immutable reference
⚓ Rust 📅 2026-02-15 👤 surdeus 👁️ 6Hello everyone,
I have some code which fails to compile because of the error
cannot return value referencing local variable `word`
...
returns a value referencing data owned by the current function
However, I can't make sense out of the error because the function doesn't return a reference to its local data.
This is the concise version of the code.
struct Word;
static STATIC_WORD: Word = Word;
enum State {
Loading,
Ready {
word: Word,
}
}
impl State {
fn obtain_payload<'a>(&'a mut self) -> &'a Word {
match self {
Self::Loading => &STATIC_WORD,
Self::Ready { word } => &word,
}
}
}
fn main() {
let mut state = State::Loading;
let _payload = state.obtain_payload();
}
Based on the chapter Subtyping and Variance,
I have the following guess. The function takes in a mutable reference &mut self.
Given the chapter:
- Mutable references are invariant.
- Immutable references are covariant.
Given the definitions, an immutable reference can refer to data which lives at least as long it does (longer or the same). Based on that,
a reference to static data can substitute a reference to a field. However, the immutable reference in the function
is connected to the mutable reference; therefore, it becomes invariant. Based on the definition of invariance,
the reference must refer to data which lives exactly the expected period of time (which is 'a).
Therefore, the 'static can't be used here and the compiler gives the error.
Do I understand correctly?
2 posts - 2 participants
🏷️ Rust_feed