从子结构获取值,然后修改子结构:借用检查器拼图?

时间:2017-12-03 21:20:42

标签: rust borrow-checker

考虑这个玩具代码:

struct X {
    x: usize,
    times_accessed: usize,
}

impl X {
    fn get(&mut self) -> usize {
        self.times_accessed = self.times_accessed + 1;
        self.x
    }
}

struct Y {
    y: usize,
    max_access: usize,
    option_x: Option<X>,
}

impl Y {
    fn get_x(&mut self) -> Option<usize> {
        match self.option_x {
            Some(ref mut some_x) => {
                let result = some_x.get();

                if some_x.times_accessed == self.max_access {
                    self.option_x = None;
                }

                Some(result)
            }
            None => {
                println!("option_x is not initialized! try calling Y::init_x");
                None
            }
        }
    }

    fn init_x(&mut self, x_val: usize, max_allowed_access: usize) {
        self.max_access = max_allowed_access;
        self.option_x = Some(X {
            x: x_val,
            times_accessed: 0,
        });
    }
}

fn main() {
    println!("hello world!");
}

我没有在主函数中使用Y,因为编译器不需要我这样做来指出借用检查器不会对Y::get_x的实现感到满意:

error[E0506]: cannot assign to `self.option_x` because it is borrowed
  --> src/main.rs:26:21
   |
22 |             Some(ref mut some_x) => {
   |                  -------------- borrow of `self.option_x` occurs here
...
26 |                     self.option_x = None;
   |                     ^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.option_x` occurs here

我从借用检查器的角度理解这个问题,我可以提出一个非常简单的解决方法:将some_x的值复制到result(毕竟,我还没有这样做,结果不是引用,usize具有Copy特征),然后将“引用”删除到some_x(它会使用drop(some_x);,所以我可以修改option_x?这里提供的版本,但仍然不起作用:

fn get_x(&mut self) -> Option<usize> {
    match self.option_x {
        Some(ref mut some_x) => {
            let result = some_x.get();

            if some_x.times_accessed == self.max_access {
                drop(some_x);
                self.option_x = None;
            }

            Some(result)
        }
        None => {
            println!("option_x is not initialized! try calling Y::init_x");
            None
        }
    }
}

应该怎么做?

1 个答案:

答案 0 :(得分:1)

正如错误消息所述,当您在其中引用某些内容时,您正试图替换self.option_x

Some(ref mut some_x) => {
    let result = some_x.get();

    if some_x.times_accessed == self.max_access {
        self.option_x = None; // <---------
    }

    Some(result)
}

访问some_x的突出显示点之后的任何代码都会获得无效值。这就是程序崩溃,暴露安全漏洞等的方式。

在潜在的Rust未来,理解非词汇生存期的编译器可能会意识到您没有使用该值,因此代码在当前状态下是正常的。在此之前,您可以从Option中取出全部价值,然后在不符合条件的情况下将其取回:

match self.option_x.take() {
    Some(mut some_x) => {
        let result = some_x.get();

        if some_x.times_accessed != self.max_access {
            self.option_x = Some(some_x);
        }

        Some(result)
    }

另见: