How does the compiler know that Vec<&T> must be survived by all pointees?
⚓ Rust 📅 2025-12-12 👤 surdeus 👁️ 1Consider the following code (playground):
#[derive(Debug)]
struct Struct;
fn main() {
let s = Struct;
let mut v = Vec::new();
v.push(&s);
drop(s); // Error: cannot move out of `s` while `s` is borrowed
println!("{:?}", v);
}
The compiler complains that drop(s) is illegal here because it attempts to move the value out of s while it is still borrowed. But how does the compiler know that the borrow of s lives a long as v and is therefore must still be valid when println!("{:?}", v); is called? What is it about the signature of Vec::push(&mut self, value: T) that tells the borrow checker that all pointees of reference-typed values must live at least as long as this Vec does?
4 posts - 3 participants
🏷️ Rust_feed