Rust 调用方法参考
Rust call method on reference
作为 Rust 的新手,我找到了很多关于这个问题的资源,但是 none 这确实可以帮助我。
我想要做的是引用一个结构并调用它的方法。
最小化示例:
// 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
的实例存在于堆上并仍然调用它的方法?
由于您的 get_rating
也令人惊讶地修改了实例,因此您需要使其可变。首先是 Box
,然后是引用也应该是可变的。
let mut mybox : Box<RatedCharacter> = create_rated_character(2 as f64,4 as f64);
let mychar : &mut RatedCharacter = mybox.as_mut();
mychar.get_rating();
作为 Rust 的新手,我找到了很多关于这个问题的资源,但是 none 这确实可以帮助我。 我想要做的是引用一个结构并调用它的方法。
最小化示例:
// 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
的实例存在于堆上并仍然调用它的方法?
由于您的 get_rating
也令人惊讶地修改了实例,因此您需要使其可变。首先是 Box
,然后是引用也应该是可变的。
let mut mybox : Box<RatedCharacter> = create_rated_character(2 as f64,4 as f64);
let mychar : &mut RatedCharacter = mybox.as_mut();
mychar.get_rating();