Be aware that while a Box
does in fact fix your problem on the surface, it makes it impossible to actually create an instance of it if you intend to have a bidirectional link between the partners:
struct Person {
partner: Option<Box<Person>>,
}
pub fn main() {
let susan = Person { partner: None };
let mut john = Person {
partner: Some(Box::new(susan)),
};
// This moves `susan` into `john`, meaning `susan` is now only
// accessible through `john.partner`.
let susan = john.partner.as_mut().unwrap();
// It is literally impossible to set john as a partner of susan,
// no matter what you try. (without using `unsafe`)
susan.partner = Some(Box::new(john));
}
error[E0505]: cannot move out of `john` because it is borrowed
--> src/main.rs:18:35
|
14 | let susan = john.partner.as_mut().unwrap();
| --------------------- borrow of `john.partner` occurs here
...
18 | susan.partner = Some(Box::new(john));
| ------------- ^^^^ move out of `john` occurs here
| |
| borrow later used here
Box
is only useful if you have a tree-like ownership chain, where someone owns the topmost item.
Your situation is not completely lost, however, just a little more complicated.
For once, you could use Rc
instead of Box
to do this. This is a little dangerous, though, because a circular Rc
chain will leak and never be dropped unless you manually break the cycle at some point. Remember, Rust does not have a garbage collector.
One solution that I could see is Weak
, which is a version of Rc
that specifically does not keep the object it points to alive. It is made specifically for circular references like this. Note, however, that this makes the objects immutable and therefore we need to create interior mutability with RefCell
.
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
#[derive(Debug)]
struct Person {
name: String,
partner: Option<Weak<RefCell<Person>>>,
}
impl Person {
fn partner_name(&self) -> Option<String> {
self.partner
.as_ref()
.map(|partner| Weak::upgrade(partner).unwrap())
.map(|partner| RefCell::borrow(&partner).name.clone())
}
}
pub fn main() {
let susan = Rc::new(RefCell::new(Person {
name: "Susan".to_string(),
partner: None,
}));
let john = Rc::new(RefCell::new(Person {
name: "John".to_string(),
partner: Some(Rc::downgrade(&susan)),
}));
// Now we can actually set them to be each other's partner:
RefCell::borrow_mut(&susan).partner = Some(Rc::downgrade(&john));
// Both `susan` and `john` are still accessible
println!("John: {:?}", john);
println!(
"John's partner: {:?}\n",
RefCell::borrow(&john).partner_name()
);
println!("Susan: {:?}", susan);
println!(
"Susan's partner: {:?}\n",
RefCell::borrow(&susan).partner_name()
);
// Note that `susan` and `john` do not keep each other alive, as they
// are only `Weak` references. Therefore dropping the `Rc` handle
// Will cause the `Weak` handle to lose the connection.
drop(susan);
println!("John's partner after dropping Susan:");
println!("{:?}", RefCell::borrow(&john).partner_name());
}
John: RefCell { value: Person { name: "John", partner: Some((Weak)) } }
John's partner: Some("Susan")
Susan: RefCell { value: Person { name: "Susan", partner: Some((Weak)) } }
Susan's partner: Some("John")
John's partner after dropping Susan:
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:16:51