首页 > 解决方案 > 非复制或克隆的全局常量如何在 Rust 中工作?

问题描述

假设我有以下片段(游乐场

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 没有多大意义,并且如图所示,无论如何都不是这种情况,因为它可以“移动”两次。

A考虑到not Clonenor ,允许上述代码段工作的规则是Copy什么?

标签: rustconstantsmove

解决方案


常量总是内联的。你的例子基本上是一样的

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);
}

该值被重建两次,因此它不需要是Copyor Clone

另一方面,statics 没有内联:

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`

推荐阅读