Lazy_static! native

Hello,

I've noticed that for a large majority of the projects I've coded in Rust, I've needed to use shared globals statics data. And the only way to do this safely is to use Crate lazy_static .

Ex:

lazy_static! {
    static ref TOKIO_RUNTIME: tokio::runtime::Runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .expect("TOKIO RUNTIME ERROR");
    static ref ACTIONS_QUEUE: Arc<Mutex<VecDeque<WaitingAction>>> = Arc::new(Mutex::new(VecDeque::new()));
}

Wouldn't it be easier to do this natively in Rust without having to use a Crate (and therefore a compile-time cost to interpret the Macros)?

2788-standard-lazy-types - The Rust RFC Book, which is already implemented, and part of it is already stabilized.

5 Likes

Also note that there is no need to use Arc in static, and Mutex::new() and VecDeque::new() are already const, so the second static can be a normal static:

static ACTIONS_QUEUE: Mutex<VecDeque<WaitingAction>> = Mutex::new(VecDeque::new());
4 Likes

Thank you very much for this information.

you're absolutely right, I didn't pay any attention to this detail, the memory location is static, so Arc has no use here. Thanks again :pray:

There's also the once_cell crate that does something similar without using macros.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.