【问题标题】:Rust call method on reference参考上的 Rust 调用方法
【发布时间】: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 '&amp;' reference

我怎样才能让RatedCharacter 的实例在堆上存在并且仍然调用它的方法?

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    由于您的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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 2019-05-06
      • 2021-03-09
      • 2015-09-23
      相关资源
      最近更新 更多