I am trying to create a disjoint set structure in Rust. It looks like this
struct DisjointSet<'s> {
id: usize,
parent: &'s mut DisjointSet<'s>,
}
The default disjoint set is a singleton structure, in which the parent refers to itself. Hence, I would like to have the option to do the following:
let a: DisjointSet = DisjointSet {
id: id,
parent: self,
};
where the self is a reference to the object that will be created.
I have tried working around this issue by creating a custom constructor. However, my attempts failed because partial initialization is not allowed. The compiler suggests using Option<DisjointSet<'s>>, but this is quite ugly. Do you have any suggestions?
My question differs from Structure containing fields that know each other because I am interested in getting the reference to the struct that will be created.
newfunction that constructs an instance and then patches it up before returning?&mutwon't work anyway for parent references anyway, since it does not allow aliasing.&allows that but still requires some gymnastics (and aCellif you want to changeidafter construction). It also puts weird requirements on the collection of allDisjointSets (can't haveVec<DisjointSet<'s>>for example). A disjoint set data structure is effectively a DAG, i.e. a graph, and graphs are hairy to encode in Rust. I'm inclined to recommend the traditional implementation via indices (parent: usize, implicitly referring to aVec<DisjointSet>somewhere else).