为什么在同一范围内可以有多个具有静态生命周期的可变引用

Why is it possible to have multiple mutable references with static lifetime in same scope

为什么我可以在同一范围内对静态类型有多个可变引用?

My code:

static mut CURSOR: Option<B> = None;

struct B {
    pub field: u16,
}

impl B {
    pub fn new(value: u16) -> B {
        B { field: value }
    }
}

struct A;

impl A {
    pub fn get_b(&mut self) -> &'static mut B {
        unsafe {
            match CURSOR {
                Some(ref mut cursor) => cursor,
                None => {
                    CURSOR= Some(B::new(10));
                    self.get_b()
                }
            }
        }
    }
}

fn main() {
    // first creation of A, get a mutable reference to b and change its field.
    let mut a = A {};
    let mut b = a.get_b();
    b.field = 15;
    println!("{}", b.field);

    // second creation of A, a the mutable reference to b and change its field.
    let mut a_1 = A {};
    let mut b_1 = a_1.get_b();
    b_1.field = 16;
    println!("{}", b_1.field);

    // Third creation of A, get a mutable reference to b and change its field.
    let mut a_2 = A {};
    let b_2 = a_2.get_b();
    b_2.field = 17;
    println!("{}", b_1.field);

    // now I can change them all
    b.field = 1;
    b_1.field = 2;
    b_2.field = 3;
}

我知道 borrowing 规则

在上面的代码中,我有一个结构 A,它带有 get_b() 方法,用于返回对 B 的可变引用。有了这个引用,我可以改变 struct B 的字段。

奇怪的是在同一作用域(b, b_1, b_2) 中可以创建多个可变引用,而我可以使用所有这些引用来修改B

为什么 main() 中显示的 'static 生命周期可以有多个可变引用?

我试图解释这种行为是因为我返回了一个生命周期为 'static 的可变引用。每次我调用 get_b() 时,它都会返回相同的可变引用。最后,它只是一个相同的参考。这个想法对吗?为什么我能够单独使用从 get_b() 获得的所有可变引用?

只有一个原因:你对编译器撒了谎。您在滥用 unsafe 代码并且违反了 Rust 关于可变别名的核心原则。你声明你知道借用规则,但你 特意违反它们 !

unsafe 代码给你 a small set of extra abilities, but in exchange you are now responsible for avoiding every possible kind of undefined behavior。多个可变别名是未定义的行为。

涉及 static 的事实与问题完全正交。无论你关心什么生命周期,你都可以创建对任何东西(或什么都没有)的多个可变引用:

fn foo() -> (&'static i32, &'static i32, &'static i32) {
    let somewhere = 0x42 as *mut i32;
    unsafe { (&*somewhere, &*somewhere, &*somewhere) }
}

在您的原始代码中,您声明调用 get_b 对任何人调用任意次数都是安全的。这不是真的。整个功能应该被标记为不安全的,以及关于什么是允许的和什么是不允许的以防止触发不安全的大量文档。任何 unsafe 块都应该有相应的注释来解释为什么 that 特定用法不会违反所需的规则。所有这些使得创建和使用 unsafe 代码比安全代码更乏味,但与 C 相比,其中 行代码在概念上是 unsafe,它仍然很多更好。

当您比编译器更了解时,您应该只使用 unsafe 代码。在大多数情况下,对于大多数人来说,几乎没有理由创建 unsafe 代码。

来自the Firefox developers的具体提醒: