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


20

说我有以下片段(游乐场

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既不是也不CloneCopy,我假设的值GLOBAL_A将被移动。这对于const来说没有多大意义,而且无论如何也无法显示,因为它可以被“移动”两次。

允许以上代码片段起作用的规则A是什么Clone也不是Copy

Answers:


21

常量总是内联的。您的示例与以下示例基本相同

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`
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.