多重可变参考预防在Rust中如何工作? [英] How does multiple mutable reference prevention work in Rust?

查看:77
本文介绍了多重可变参考预防在Rust中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么允许这样做:

  fn main(){
let mut w = MyStruct;
w.fun1();
}

结构MyStruct;

impl MyStruct {
fn fun1(& mut self){
self.fun2();
}

fn fun2(& mut self){
println!( Hello world 2);
}
}

在上面的代码 fun1 ()获取 mut MyStruct 并使用 fun2() > mut MyStruct 。是在一个范围内双重可变引用吗?

解决方案

这是允许的,因为借阅检查器可以得出结论:只有一个可变引用存在在执行期间访问。在运行 fun2 时,没有执行 fun1 中的其他语句。当 fun1 中的下一条语句(如果有)开始执行时, fun2 已经删除了其可变引用。 / p>

在链接的另一个问题中:

  fn main(){
let mut x1 = String :: from( hello);
令r1 =& mut x1;
让r2 =& mut x1;

r1.insert(0,‘w’);
}

我们可以说 r2 从未使用过,但是借位检查器决定不应使用它。考虑以下示例:

  fn main(){
let mut x1 = String: :from( hello);
令r1 =& mut x1;
r1.insert(0,‘w’);

令r2 =& mut x1;
r2.insert(0,‘x’);
}

这将正确编译并运行。我假设借位检查器假设生存期 r1 在创建 r2 之前结束。如果这是有道理的,那么调用使 self 自身发生突变的方法就不会感到惊讶。



(我不会知道为什么第一段代码无法编译,但是我很高兴锈团队做到了。 r2 不应存在。)


Why it is allowed to do something like this:

fn main() {
    let mut w = MyStruct;
    w.fun1();
}

struct MyStruct;

impl MyStruct {
    fn fun1(&mut self) {
        self.fun2();
    }

    fn fun2(&mut self) {
        println!("Hello world 2");
    }
}

In the above code fun1() gets mut MyStruct and calls fun2() also with mut MyStruct. Is it double mutable reference in one scope?

解决方案

This is allowed because the borrow checker can conclude there is only one mutable reference being accessed during execution. While fun2 is running, no other statement in fun1 is being executed. When the next statement in fun1 (if there was any) starts executing, fun2 has already dropped its mutable reference.

In the other question linked:

fn main() {
    let mut x1 = String::from("hello");
    let r1 = &mut x1;
    let r2 = &mut x1;

    r1.insert(0, 'w');
}

We can say r2 is never used, but borrow checker decided it shouldn't be allowed. Consider this example:

fn main() {
    let mut x1 = String::from("hello");
    let r1 = &mut x1;
    r1.insert(0, 'w');

    let r2 = &mut x1;
    r2.insert(0, 'x');
}

This compiles and runs correctly. I suppose borrow checker assumes the lifetime r1 ends before r2 is created. If this makes sense, calling methods that mutate self shouldn't be so surprising.

(I don't know why the 1st piece of code does not compile, but I am glad rust team made it that way. r2 should not be there anyway.)

这篇关于多重可变参考预防在Rust中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆