如果您的变量不打算更改,则没有太大的实际区别。
常量在编译时内联,这意味着它们被复制到它们使用的每个位置,因此通常更有效,而静态引用内存中的唯一位置,更像是全局变量。
常量是......常量而静态,虽然仍然是全局的,但可以是可变的。
constRust中的变量是不可变的.你既不能重新分配也不能修改它:
struct Foo(u32);
const FOO: Foo = Foo(5);
fn main() {
FOO = Foo(1); //illegal
FOO.0 = 2; //illegal
}
Run Code Online (Sandbox Code Playgroud)
甲static变量可以是可变的,并且因此可以被修改或重新分配.请注意,写入/修改全局static变量是不安全的,因此需要一个unsafe块:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
编译二进制文件时,所有const"出现"(在const源代码中使用它的位置)将直接替换为该值.
statics将在二进制文件中放置一个专门的部分(BSS部分,请参阅C和C++中存储的静态变量在哪里?以获取更多信息).
总而言之,const尽可能坚持下去.如果不可能,因为您需要在非const方法的程序中稍后初始化变量,请使用lazy_static!.
staticvsconstconst:
staticstatic:
例子:
static CDF: i32 = 100;
const ABC: i32 = 50;
fn main() {
println!("{}", CDF); // compiler will put in a load instruction here for the static address
println!("{}", ABC); // compiler will put the value 50 here directly
// statics can be mutable
static mut HI: &str = "hi";
// however using mut static is unsafe
unsafe {
HI = "HITHERE";
}
unsafe {
println!("{}", HI);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1403 次 |
| 最近记录: |