如何在Rust中编写静态变量的集合



我想收集像java 这样的静态变量

Class A {
public static final String HELLO = "hello";
public static final String WORLD = "world";
}

但是Rust中的enum或struct不支持它!我应该使用类似static HashMap的东西吗?

这方面最直接的转换是"相关常数":

struct A { /* .. */ }
impl A {
const HELLO: &str = "hello";
const WORLD: &str = "world";
}

其将经由CCD_ 2和CCD_。


但是,如果您不打算使用A,而只是想将其作为一种作用域机制,那么您应该使用一个模块:

mod constants {
const HELLO: &str = "hello";
const WORLD: &str = "world";
}

其将经由CCD_ 5和CCD_。


如果你想把它作为一个静态哈希图,它看起来像这样:

use std::collections::HashMap;
use once_cell::sync::Lazy; // 1.15.0
static A: Lazy<HashMap<&str, &str>> = Lazy::new(|| {
let mut map = HashMap::new();
map.insert("HELLO", "hello");
map.insert("WORLD", "world");
map
});

在Rust中,static变量必须用const表达式初始化,但由于插入到HashMap中不是const,因此我们可以使用once cell crate中的Lazy对其进行延迟初始化。这显然与访问不同,因为它不是一组已知的定义:A.get("HELLO").unwrap()

最新更新