不是复制或克隆的全局常量如何在 Rust 中工作?

How do global consts that are not copy or clone work in Rust?

假设我有以下片段 (playground)

struct A {
    pub val: u32
}

const GLOBAL_A: A = A {val: 2};

fn main() {
    let some_a: A = GLOBAL_A;
    let other_a: A = GLOBAL_A;

    println!("double val = {}", some_a.val + other_a.val);
}

因为 A 既不是 Clone 也不是 Copy,我假设 GLOBAL_A 的值会被移动。这对于 const 没有多大意义,如图所示无论如何都不是这种情况,因为它可以是 "moved" 两次。

考虑到 A 既不是 Clone 也不是 Copy,允许上述代码段工作的规则是什么?

常量总是内联的。您的示例与

基本相同
struct A {
    pub val: u32
}

fn main() {
    let some_a: A = A {val: 2};
    let other_a: A = A {val: 2};

    println!("double val = {}", some_a.val + other_a.val);
}

该值被重构了两次,所以不需要CopyClone

另一方面,static没有内联:

struct A {
    pub val: u32
}

static GLOBAL_A: A = A {val: 2};

fn main() {
    let some_a: A = GLOBAL_A;
}

结果

error[E0507]: cannot move out of static item `GLOBAL_A`
 --> src/main.rs:8:21
  |
8 |     let some_a: A = GLOBAL_A;
  |                     ^^^^^^^^
  |                     |
  |                     move occurs because `GLOBAL_A` has type `A`, which does not implement the `Copy` trait
  |                     help: consider borrowing here: `&GLOBAL_A`