我想收集静态变量,比如java。
Class A {
public static final String HELLO = "hello";
public static final String WORLD = "world";
}但它不支持的枚举或结构中的锈!我应该用像static HashMap这样的东西吗?
发布于 2022-10-04 04:01:40
最直截了当的转换是“关联常量”:
struct A { /* .. */ }
impl A {
const HELLO: &str = "hello";
const WORLD: &str = "world";
}可以通过A::HELLO和A::WORLD访问。
但是,如果您不打算使用A并且只希望它作为一个作用域机制,那么您应该使用一个模块:
mod constants {
const HELLO: &str = "hello";
const WORLD: &str = "world";
}可以通过constants::HELLO和constants::WORLD访问。
如果您希望将其作为静态散列映射,则如下所示:
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,所以我们可以从一次单元格箱中使用Lazy来延迟初始化它。这显然与access不同,因为它不是一组已知的定义:A.get("HELLO").unwrap()
https://stackoverflow.com/questions/73942814
复制相似问题