I am trying to build a molecule data structure. Starting with an Atom
struct, a molecule Vec
stores all of the Atom
s (with their coordinates and indices, etc). I also want a Bond
struct which will have pairs of Atom
structs, and another Vec
which stores all of the bonds. I'll do the same for Angle
and so on...
Once in the structs, the data will not be mutated, it will just be used to calculate things like bond lengths via methods, but I can't quite work out how to get around the ownership issue.
mvp_molecule.rs
#[derive(Debug)]
struct Atom {
atomic_symbol: String,
index: i16,
}
#[derive(Debug)]
struct Bond {
atom_1: Atom,
atom_2: Atom,
}
pub fn make_molecule() {
let mut molecule = Vec::new();
let mut bonds = Vec::new();
let atom_1 = Atom {
atomic_symbol: "C".to_string(),
index: 0,
};
molecule.push(atom_1);
let atom_2 = Atom {
atomic_symbol: "H".to_string(),
index: 1,
};
molecule.push(atom_2);
let bond = Bond {
atom_1: molecule[0],
atom_2: molecule[1],
};
bonds.push(bond);
}
I think the issue is that Rust thinks I might change an Atom
while it's in a Bond
, which I won't do. How can I convince Rust of that?
I appreciate this may be a common problem but I'm not learned enough to realise what I should be looking for to solve it. I've looked through a lot of the documentation on references, borrowing and lifetimes but I'm still not quite sure what the issue I'm trying to solve is, or if it's solvable in this way.