#thread-local #local #thread #variables #global

with-thread-local

一个简化使用std宏thread_local!的微库。

1个稳定版本

1.0.0 2023年1月11日

#2425Rust模式

MIT/Apache

7KB
51

Rust Latest Version Rust 1.46+ License Docs.rs LOC Dependency Status

with-thread-local

一个简化使用std宏thread_local!的微库。

extern crate regex;

use with_thread_local::with_thread_local;
use regex::Regex;

let user_input = "cat";

let (is_a_pet, needs_a_walk) = with_thread_local! {
    static REGEX_PET: Regex = Regex::new(r"cat|dog").unwrap();
    static REGEX_WALK: Regex = Regex::new(r"dog").unwrap();

    {
        let is_a_pet = REGEX_PET.is_match(user_input);
        let needs_a_walk = REGEX_WALK.is_match(user_input);

        (is_a_pet, needs_a_walk)
    }
};

assert!(is_a_pet && !needs_a_walk);

您还可以使用其变体move在块内移动变量。尽管我承认我无法编写一个很好的例子

extern crate regex;

use with_thread_local::with_thread_local;
use regex::Regex;

let user_input = vec!["cat", "love", "dog"];

let output = with_thread_local! {
    static REGEX_PET: Regex = Regex::new(r"cat|dog").unwrap();

    move {
        user_input
            .into_iter()
            .filter(|s| REGEX_PET.is_match(s))
            .collect::<Vec<_>>()
    }
};

assert_eq!(output, ["cat", "dog"]);

无运行时依赖