Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
user2089648 Avatar asked Nov 20 '25 06:11

user2089648


1 Answers

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();
like image 76
Leśny Rumcajs Avatar answered Nov 22 '25 18:11

Leśny Rumcajs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!