【发布时间】:2020-02-08 09:27:58
【问题描述】:
对于 rust 来说相当陌生,这是一个我找到很多资源的问题,但没有一个能真正帮助我。 我想做的是引用一个结构并调用它的方法。
最小化的例子:
// 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 的实例在堆上存在并且仍然调用它的方法?
【问题讨论】:
标签: rust borrow-checker