Будучи довольно новым для ржавчины, это проблема, о которой я нашел много ресурсов, однако ни один из них не мог мне помочь. Я хочу сделать ссылку на структуру и вызвать ее метод.
Минимизированный пример:
// 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();
}
Компилятор жалуется на cannot borrow '*mychar' as mutable, as it is behind a '&' reference
.
Как я могу позволить экземпляру RatedCharacter
жить в куче и по-прежнему вызывать его методы?