Reference Arena, then mutate values inside Arena

Viewed 63

When using the generational-arena crate, is there anyway to reference an entity in the arena, and then use that reference to assign new values a mutable reference to other entities in the arena? This seems you'd want your entities to be able to do.

generational-arena = "0.2.8"
use generational_arena::{Arena};
fn main(){
    let mut arena = Arena::new();

    // Insert some elements into the arena.
    let rza = arena.insert("Robert Fitzgerald Diggs");
    let gza = arena.insert("Gary Grice");
    let bill = arena.insert("Bill Gates");
    
    //combine rza and gza and assign to bill
    let rza_val = arena.get(rza).unwrap();
    let gza_val = arena.get(gza).unwrap();
    let mut_bill = arena.get_mut(bill).unwrap();
    *mut_bill = &format!("{}, {}",*rza_val, *gza_val);
}
1 Answers

One simple way would be to play with the scopes, so the inmutable borrowing are gone before you borrow it mutable again:

let new_bill = {
    let rza_val = arena.get(rza).unwrap();
    let gza_val = arena.get(gza).unwrap();
    format!("{}, {}", rza_val, gza_val)
};
let mut_bill = arena.get_mut(bill).unwrap();
*mut_bill = &new_bill;
Related