常量和静态变量之间有什么区别,我应该选择哪个? [英] What is the difference between a constant and a static variable and which should I choose?

查看:88
本文介绍了常量和静态变量之间有什么区别,我应该选择哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 RFC 246知道这一点:

  • 常数声明常数值.这些代表一个值,而不是一个内存地址.这是我们目前所知的几乎所有情况下可以达到的最普遍的方法,它将取代 static .
  • 静态声明全局变量.这些代表一个内存地址.它们将很少使用:主要用例是全局锁,全局原子计数器以及与旧版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.

我应该选择哪个?

推荐答案

易变性

Rust中的 const ant是不可变的.您既不能重新分配也不能修改它:

Mutability

A constant 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
}

一个 static 变量 是可变的,因此可以修改或重新分配.请注意,编写/修改全局 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 "occurrences"(您在源代码中使用 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.

静态将在二进制文件中有一个专用部分( BSS部分,请参见

statics 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 方法初始化变量,请使用

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!.

这篇关于常量和静态变量之间有什么区别,我应该选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆