gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:36:36 26 4
gpt4 key购买 nike

说我有以下片段(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的值将被 move 。对于const来说,这没有多大意义,而且由于它可以被“move ”两次,因此无论如何都不可能如此。

考虑到 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`

关于rust - 不是复制或克隆的全局const在Rust中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com