I'm trying to write a container for objects of type T
which provides access to references &T
to the stored objects (I want to avoid making copies). Since the container only ever grows during its lifetime, the lifetime of the returned references &T
should be the same as for the container.
The closest I got so far was to use Box<T>
objects internally in my container and use Box<T>.as_ref()
to return references to these objects. Then, however, I run into the same problem as in this minimal example:
fn main() {
let mut v = vec![Box::new(1)]; // line 1
let x = v[0].as_ref(); // line 2: immutable borrow occurs here
println!("x = {:?}", x); // line 3
v.push(Box::new(2)); // line 4: mutable borrow occurs here -> error
println!("x = {:?}", x); // line 5
}
I understand that it would be unsound to use x
in line 5 if it had been deleted from v
during the the mutable borrow. But that's not the case here, and it'll never be for my container. If there's no safe way to express this in Rust, how could I "repair" the example (without copying x
)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…