简体   繁体   English

Rust多次可变借用

[英]Rust multiple mutable borrowing

I'm trying Rust and have issues with understanding "borrowing". 我正在尝试Rust并且在理解“借用”方面存在问题。

struct Foo<T> {
    data: T,
}

impl<T> Foo<T> {
    fn new(data: T) -> Self {
        Foo {
            data: data,
        }
    }
}

fn main() {
    let mut foo = Foo::new("hello");

    let x = &mut foo;
    let y = &mut foo;

    println!("{}", foo.data);

}

Why this code compile without error? 为什么这段代码编译没有错误? After all, I'm get a multiple mutable references on foo . 毕竟,我在foo上获得了多个可变引用。 The following is written to documentation: 以下内容写入文档:

The Rules of References 参考规则
Let's recap what we've discussed about references: 让我们回顾一下我们讨论的关于参考文献的内容:

a) At any given time, you can have either (but not both of) one mutable reference or any number of immutable references. a)在任何给定时间,您可以拥有(但不是两个)一个可变引用或任意数量的不可变引用。

b) References must always be valid. b)参考文献必须始终有效。

What is the reason for this behavior? 这种行为的原因是什么? Thanks! 谢谢!

You are probably benefiting from non-lexical lifetimes which have been enabled by default since Rust 1.30 while using the 2018 edition. 你可能从非词法生命期中受益,这些生命周期自Rust 1.30使用2018版以来默认启用

See also What are non-lexical lifetimes? 另请参见什么是非词汇生命周期? .

On my rust version (1.29.1), I do have the multi-borrow errors. 在我的防锈版本(1.29.1)上,我确实有多借用错误。

I think you are benefiting from non-lexical lifetimes here, that or the compiler smartly optimizes* the code as: 我认为你从这里的非词汇生命周期中受益,或者编译器巧妙地将代码优化为:

let mut foo = Foo::new("hello");

{ let x = &mut foo; }
{ let y = &mut foo; }

println!("{}", foo.data);

which works because you are not using x and y . 这是有效的,因为你没有使用xy

*: from @mcarton: optimizations occurs after the borrow-check pass, so the only option is NLL. *:来自@mcarton:借用 - 检查通过后发生优化,因此唯一的选择是NLL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM