rust - 非复制或克隆的全局常量如何在 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 Clone
nor ,允许上述代码段工作的规则是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);
}
该值被重建两次,因此它不需要是Copy
or Clone
。
另一方面,static
s 没有内联:
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`
推荐阅读
- php - 具有不同引导列的 Wordpress 循环
- mysql - MySQL Query 在 id 列对应的多行中添加值
- django - 得到一个 FATAL Exited too faster 错误。主管配置
- unity3d - unity2d 字符 y 位置等于鸟 y 位置
- java - java - 如何在没有jsoup的Java中仅使用正则表达式解析HTML TAG
- angular - ng-packagr npm 安装错误:postinstall `opencollective postinstall`
- javascript - 是否有标准或推荐的方法来使用 JSON 中由冒号分隔的部分值?
- python-3.x - 如何修复'ValueError(“输入必须不止一个句子”)'错误
- node.js - 如何在安装了节点的情况下构建 Docker 映像
- javascript - 使用 Webpack 的 DefinePlugin 动态地需要多个文件?