Append to Vec in nested Struct

Dear all,

I am new to Rust and hoped to get some help here. I am trying to write a function that parses a file containing some data and store the data as a nested struct.

    struct Atom {
        atom_id: usize,
        atom_name: String,
        coords: [f64; 3],
        qm: f64,
        active: f64,
        element: String,
    }

    struct Residue {
        res_name: String,
        res_id: usize,
        atoms: Vec<Atom>,
    }

The parser function looks like:

fn parse_pdb(path: &str) -> Vec<Residue> {
    let f = File::open(path).expect(&format!("Couldn't open file: {}", path));
    let f = BufReader::new(f);
    let mut molecule: Vec<Residue> = Vec::new();

    for (index, line) in f.lines().enumerate() {
        let l = line.expect(&format!("Couldn't read line {}", index));

        if l.starts_with("ATOM") || l.starts_with("HETATM") {
            let atom = Atom {
                atom_id: l[6..11].trim().parse().expect(
                    &format!("Couldn't parse atom ID in line {}", index)),
                atom_name: l[12..16].trim().to_string(),
                coords: [
                    l[30..38].trim().parse().unwrap(),
                    l[38..46].trim().parse().unwrap(),
                    l[46..54].trim().parse().unwrap(),
                ],
                qm: l[54..60].trim().parse().unwrap(),
                active: l[60..66].trim().parse().unwrap(),
                element: l[76..78].trim().to_string(),
            };

            if atom.atom_name == "N" {
                let mut residue = Residue {
                    res_name: l[17..20].trim().to_string(),
                    res_id: l[22..26].trim().parse().unwrap(),
                    atoms: Vec::new(),
                };
            molecule.push(residue);
            }
            residue.atoms.push(atom);
            //molecule.last().unwrap().atoms.push(atom);
        }
    }

    assert!(!molecule.is_empty(), "No Atoms could be parsed! Please make sure
            you have a valid PDB file.");
    molecule
}

This won't compile because the variable residue is not available after the if-clause in which it is defined. If I try to push to the last element of molecule this will also not work because last() returns a borrowed slice that cannot be borrowed as mutable. I would appreciate any pointers as to any solutions.

Maybe last_mut can help.

That was exactly what I needed, thanks!