How can you make a safe static singleton in Rust?

前端 未结 2 833
独厮守ぢ
独厮守ぢ 2020-11-22 07:15

This is something of a controversial topic, so let me start by explaining my use case, and then talk about the actual problem.

I find that for a bunch of unsafe thin

2条回答
  •  日久生厌
    2020-11-22 07:57

    It looks like a use case for std::sync::Once:

    use std::sync::{Once, ONCE_INIT};
    static INIT: Once = ONCE_INIT;
    

    Then in your tests call

    INIT.doit(|| unsafe { init(); });
    

    Once guarantees that your init will only be executed once, no matter how many times you call INIT.doit().

提交回复
热议问题