在使用 C 或 C++ 编程语言的时候,我们有时会将变量声明在函数之外,使其可以在任何时间于整个程序的任何 scope 下使用。使用 Java 编程语言的时候,也有时会替类别加上 static 的类别(静态)字段变量,甚至还可以在 static 区块中,在类别初始化的时候顺便对类别字段进行初始化的动作。我们把这类声明在函数、方法之外,且独立于对象实体的变量称为「全域静态变量」(C/C++ 的全域变量有分能给其它源代码文件使用的外部变量,与只能在同一源代码文件下使用的静态变量),通常用来保存在不同函数、方法间共享的数据。「静态」的涵意是变量在编译阶段的时候,编译器就会给定其初始值,因此只能给定在编译阶段时就能知道运算结果的表达式。「静态」的值所使用的内存空间,在程序的运行阶段会持续存在。
C 语言的全域静态变量范例:
#include<stdio.h>
static int counter = 0;
int main(){
counter++;
printf("%d\n", counter);
return 0;
}
Java 的全域静态变量范例:
public class MyClass {
static int counter = 0;
public MyClass(){
counter++;
}
public static int getCount(){
return counter;
}
}
无论是在 C 语言或是 Java 语言中,静态变量都是可以在任何地方进行改值的,但是在 Rust 编程语言中,根据这篇文章的说明,我们可以知道,若要访问可变的静态变量的值,都必须要在不安全的模式下进行。
static mut COUNTER: isize = 0;
fn main() {
unsafe {
COUNTER += 1;
}
unsafe {
println!("{COUNTER}");
}
}
静态变量也很常用来暂存需要花费不少时间才能创建出来的大的数组或是大表格,甚至能暂存某些在实体化的时候,需要花费时间进行一些程序运行阶段才能够知道运算结果的数据结构实体。以 Java 来说,由于每个类别皆拥有其实体化时所需的构造器,因此我们可以直接在声明静态变量的同时,就指定好其所保存的对象实体,或是我们也可以在类别的 static 区块中进行静态变量初始化的动作。
程序如下:
public class MyClass {
static ClassA ca1 = new ClassA(1, 2);
static ClassA ca2;
static {
int a = ca1.getValue();
ca2 = new ClassA(a, 6);
}
}
class ClassA {
private int value;
ClassA(int a, int b) {
int c = a + b;
// and something other which may take time and finally initialize the value field ...
}
int getValue(){
return value;
}
}
以上程序可以看得出,Java 对于静态变量的使用可以说是十分直觉且自由。但如果要在 Rust 编程语言中实现相同的功能,该怎么做呢?
struct StructA {
value: isize
}
impl StructA {
fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
static CA1: StructA = StructA::new(1, 2);
如果将程序写成以上这样的话,程序第 21 行会编译错误,因为编译器无法在编译阶段就利用 StructA 结构体的 new 关联函数来创建出 StructA 结构实体,并指派给 CA1 这个全域静态变量保存。所以我们要手动在程序进入之后,于适当的时机,去使用 StructA 结构体的 new 关联函数创建出 StructA 结构实体,接着再让 Rust 程序进入不安全模式来保存它。程序如下:
struct StructA {
value: isize
}
impl StructA {
fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
static mut CA1: StructA;
fn main() {
let ca1 = StructA::new(1, 2);
unsafe{
CA1 = ca1;
}
}
然而,尴尬的是,程序第 21 行还是不会编译成功,因为编译器还是不知道静态变量的值到底是什么。此时最简单的解决方案就是将静态变量的类型改为 Rust 编程语言内置的 Option 枚举类型,来包裹 StructA 类型。程序改写如下:
struct StructA {
value: isize
}
impl StructA {
fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
static mut CA1: Option<StructA> = None;
fn main() {
let ca1 = StructA::new(1, 2);
unsafe{
CA1 = Some(ca1);
}
}
但这样的作法还是会有一个小尴尬的地方是,每次在读取 CA1 静态变量的值时,我们都必须使 Rust 程序进入不安全模式,且要先经过 unwrap 的动作,从 Option 枚举取出 StructA 结构实体的参考来使用。例如:
fn use_ca1(){
let ca1 = unsafe {
CA1.as_ref().unwrap()
};
}
Option 枚举实体的 as_ref 方法可以将 Option<StructA> 转成 Option<&StructA>,如此一来使用 unwrap 方法才不会去尝试改变 StructA 结构实体的拥有者,而导致编译失败。虽然透过这样的方式是可以在 Rust 编程语言中应用全域静态变量,但实在是太麻烦了!
lazy-static.rs
有鉴于原生 Rust 编程语言对于静态变量的不友善,大多数的 Rust 开发者都选择使用 lazy_static.rs 这个套件来处理静态变量。
Crates.io
Cargo.toml
宏的使用
lazy_static.rs 提供了 lazy_static 宏,允许我们在这个宏内定义拥有初始化程序区块的静态变量。语法格式如下:
lazy_static! {
static ref 静态变量名称: 类型 = {
// 初始化程序区块
};
static ref 其它静态变量名称: 类型 = {
// 初始化程序区块
};
static ref 其它静态变量名称: 类型 = {
// 初始化程序区块
};
pub static ref 其它公开的静态变量名称: 类型 = {
// 初始化程序区块
};
}
套用 lazy_static
将我们刚才举的例子套上 lazy_static 宏来用用看,程序改写如下:
use lazy_static::lazy_static;
struct StructA {
value: isize
}
impl StructA {
fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
lazy_static! {
static ref CA1: StructA = {
StructA::new(1, 2)
};
}
fn use_ca1() {
let ca1: &StructA = &*CA1;
}
有了 lazy_static 宏后,我们就完全不需要手动初始化静态变量,而且也不用再写 unsafe 关键字,在读取静态变量的数据时,也只需要加上 * 或是 &* 做「解参考」和「取参考」的动作即可。
如果要在初始化静态变量之后,修改静态变量的值的话,为了避免在多线程下出现竞态条件的问题,必须搭配标准函数库 std::sync 模块中的 Mutex 结构体来包裹使用。有关于 Rust 的并发与并行,可以参考这篇文章。
lazy_static 宏还有一个不错的特性是,它能定义静态变量没错,但它所定义出来的静态变量在编译阶段时只需初始化智能型指针,而指针实际指到的值是在程序运行阶段,当程序第一次使用到这个静态变量的时候才会去做值的初始化动作。也就是说,就算用 lazy_static 宏声明了很多静态变量来保存很占内存或是会需要花很多时间来初始化的数据,在那个静态变量被使用到之前,完全不会占据内存(内存只会有智能型指针),也不会增加程序在一开始运行的时候的加载时间。
once_cell
once_cell 是继 lazy_static.rs 之后出现的免宏的解决方案,如果项目能够使用标准函数库的话,会比较建议使用 once_cell。相信它在不远的将来就会被正式纳入 Rust 的标准函数库中(目前还在实验阶段)。
Crates.io
Cargo.toml
使用方法
once_cell 比起 lazy_static.rs 最大的优势就是前者能够使用在一般区域变量上,可以单纯让变量的值的初始化过程只会被运行一次,之后就能重复取用第一次运行时初始化的结果。
once_cell 提供了 unsync 和 sync 模块,区域变量在单线程下可以使用 unsync 模块提供的功能,而静态全域变量要使用 sync 模块提供的功能。
程序写法如下:
use once_cell::sync::Lazy;
static 静态变量名称: Lazy<类型> = Lazy::new(|| {
// 初始化程序区块
});
套用 once_cell
将我们刚才举的例子套上 once_cell 来用用看,程序改写如下:
use once_cell::sync::Lazy;
struct StructA {
value: isize
}
impl StructA {
fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
static CA1: Lazy<StructA> = Lazy::new(|| {
StructA::new(1, 2)
});
fn use_ca1() {
let ca1: &StructA = &*CA1;
}
常数函数
在 Rust 1.31 之后,我们可以在 fn 关键字前面加上 const 使其成为常数函数。常数函数可以在编译阶段就被编译器预先运行,当它在常数、静态变量的声明等常数上下文(const context)中被调用时,编译器会在编译阶段算出它的回传值,直接取代于其被调用的位置;在其它地方被调用时,常数函数就跟一般的函数一样,会在运行阶段才被运行。
例如:
const fn return_one() -> i32 {
return 1;
}
fn main() {
let n = return_one();
println!("{n}");
}
以上程序,第 6 行的地方调用了 return_one 常数函数,但 let 叙述并不是常数上下文,所以 return_one 常数函数在这里就跟一般的函数一样,不保证会在编译阶段时被取代为它的回传值(编译器在优化程序时,还是有可能会这样做)。如果要确保 return_one 常数函数在编译阶段就被运行,可以将它的回传值指派给常数。即:
const fn return_one() -> i32 {
return 1;
}
fn main() {
const N: i32 = return_one();
println!("{N}");
}
在声明全域静态变量或者常数时,我们可以直接调用常数函数来在编译阶段取得其返回值。如下:
struct StructA {
value: isize
}
impl StructA {
const fn new(a: isize, b: isize) -> StructA {
let c = a + b;
// and something other which may take time and finally initialize the value field and return a new instance of StructA ...
// The below is just used for passing the compilation.
StructA {
value: c
}
}
fn get_value(&self) -> isize {
self.value
}
}
static CA1: StructA = StructA::new(1, 2);
将 StructA 结构体的 new 关联函数改为常数函数后,以上第 21 行的程序叙述就可以通过编译了!
