应该如何从懒惰_static迁移到std lazylock/lazycell

问题描述 投票:0回答:1

I创建了一个使用

lazy_static
创建代码其他部分可以参考以下查找值的库的库:
static
这个想法是,可以从可以导入它的任何地方访问,但它只能初始化一次,只有一个副本。我了解这种模式是实现常数hashmaps/lookup表的常见方法。

现在,它的threadsafe堂兄
HashMap

已在生锈1.80.0
中被稳定了,我一直相信这些可以替换为同样的目的。

我设法使事情与此类合作:

use lazy_static::lazy_static; use std::collections::HashMap; lazy_static! { pub static ref MAP: HashMap<&'static str, u8> = HashMap::from([("foo", 1), ("bar", 2), ("baz", 3), ("quxx", 99),]); } pub fn somefunction() { let foo = MAP.get("foo"); // Do stuff with foo value }


是从MAP
?
conther是一种更好的方法来实现常数
std::cell::LazyCell
通常? 为什么同样的事情不适合with cmpland以下内容?
std::sync::LazyLock

lazy_static


  1. 静态项目类似于常数,除了它代表程序中的精确内存位置。
    静态引用的所有引用参考相同的内存位置
    意味着静态项目必须impl
  2. LazyLock
  3. ,并且不得。
    就像如何在线程之间无法传递
    static LLMAP: LazyLock<HashMap<&str, u16>> = LazyLock::new(|| HashMap::from([("foo", 1), ("bar", 69), ("baz", 420)]));
  4. ,但是您可以使用
  5. lazy_static
    handlinghashmap
如果您只在hashmap中使用
std
,则可以将其放入函数中,它仍然是静态的,只是不会暴露于命名空间。
rust hashmap constants lazy-evaluation
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.