const变量和静态变量之间有什么区别,我应该选择哪个? [英] What is the difference between a const variable and a static variable and which should I choose?
问题描述
我从 RFC 246知道这一点:
- 常数声明恒定值。这些代表值,而不是存储器地址。这是最常见的事情,并且在今天几乎所有情况下都可以取代
static
。
- statics 声明全局变量。这些代表一个内存地址。它们将很少使用:主要用例是全局锁,全局原子计数器以及与旧版C库的接口。
- constants declare constant values. These represent a value, not a memory address. This is the most common thing one would reach for and would replace
static
as we know it today in almost all cases.- statics declare global variables. These represent a memory address. They would be rarely used: the primary use cases are global locks, global atomic counters, and interfacing with legacy C libraries.
当我尝试维护表格时,我不知道两者之间实际上有什么区别。
I don't know what is actually different between the two when I try to maintain a table.
我应该选择哪个?
推荐答案
可变性
A const $ c Rust中的$ c>变量是不可变的。您既不能重新分配也不能修改它:
Mutability
A const
variable in Rust is immutable. You neither can reassign nor modify it:
struct Foo(u32);
const FOO: Foo = Foo(5);
fn main() {
FOO = Foo(1); //illegal
FOO.0 = 2; //illegal
}
A 静态
变量可以可变,因此可以修改或重新分配。请注意,编写/修改全局 static
变量是不安全的,因此需要 unsafe
块:
A static
variable can be mutable and therefore can either be modified or reassigned. Note that writing/modifying a global static
variable is unsafe and therefore needs an unsafe
block:
struct Foo(u32);
static FOO: Foo = Foo(5);
static mut FOO_MUT: Foo = Foo(3);
fn main() {
unsafe {
FOO = Foo(1); //illegal
FOO.0 = 2; //illegal
FOO_MUT = Foo(1);
FOO_MUT.0 = 2;
}
}
发生次数
编译二进制文件时,所有 const
个出现次数(在您的二进制文件中使用该 const
源代码)将直接替换为该值。
Occurrences
When you compile a binary, all const
"occurrences" (where you use that const
in your source code) will be replaced by that value directly.
静态
s将在二进制文件中有一个专用部分( BSS部分,请参见在C和C ++?了解更多信息)。
static
s will have a dedicated section in your binary where they will be placed (the BSS section, see Where are static variables stored in C and C++? for further information).
总而言之,坚持使用 const
。在不可能的情况下,因为稍后需要在程序中使用非 const
方法初始化变量,请使用 lazy_static!
。
All in all, stick to a const
whenever possible. When not possible, because you need to initialize a variable later in the program of with non-const
methods, use lazy_static!
.
这篇关于const变量和静态变量之间有什么区别,我应该选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!