user2089648
user2089648

Reputation: 1416

Rust call method on reference

Being rather new to rust, this is an issue that I found a lot of resources about, however none that could really help me. What I want to do is have a reference to a struct and call a method of it.

Minimized example:

// A rather large struct I would want to live in the heap as to avoid copying it too often.
// Emulated by using a huge array for the sake of this example.
struct RatedCharacter {
    modifiers : [Option<f64>; 500000]
}

impl RatedCharacter {
    // A method of the large struct that also modifies it.
    fn get_rating(&mut self){
        self.modifiers[0] = Some(4.0);
        println!("TODO: GetRating");
    }
}

// A way to create an instance of the huge struct on the heap
fn create_rated_character(param1: f64, param2: f64) -> Box<RatedCharacter>{
    let modifiers : ModifierList = [None; 500000];
    do_initialisation_based_on_given_parameters();
    let result = RatedCharacter{
        modifiers : modifiers
    };
    return Box::new(result);
}

fn main() {
    let mybox : Box<RatedCharacter> = create_rated_character(2,4);
    let mychar : &RatedCharacter = mybox.as_ref();
    // The following line fails, as the borrow checker does not allow this.
    mychar.get_rating();
}

The compiler complains with cannot borrow '*mychar' as mutable, as it is behind a '&' reference.

How can I let an instance of RatedCharacter live on the heap and still call it's methods?

Upvotes: 3

Views: 2362

Answers (1)

Leśny Rumcajs
Leśny Rumcajs

Reputation: 2516

Since your get_rating is also surprisingly modifying the instance, you need to make it mutable. First the Box and then the reference should be mutable as well.

    let mut mybox : Box<RatedCharacter> = create_rated_character(2 as f64,4 as f64);
    let mychar : &mut RatedCharacter = mybox.as_mut();

    mychar.get_rating();

Upvotes: 2

Related Questions