How do I call a function that requires a 'static lifetime with a variable created in main?

前端 未结 2 1959
醉酒成梦
醉酒成梦 2020-12-17 19:51

I\'ve got a struct defined that has a function which defines a static lifetime:

impl MyStruct {
    pub fn doSomething(&\'static self) {
        // Some          


        
2条回答
  •  伪装坚强ぢ
    2020-12-17 20:30

    The naive way to do this is with a static variable, but it will require unsafe code if you need to actually set the value inside your main function:

    static mut OBJ: MyStruct = MyStruct;
    
    fn main() {
        unsafe {
            OBJ = MyStruct {};
            OBJ.doSomething();
        }
    }
    

    It's also unsafe to do pretty much anything with a mutable static thereafter.

    The much better way to do it is to let a library (lazy_static) take care of the unsafe code.

    #[macro_use]
    extern crate lazy_static;
    
    fn main() {
        lazy_static!{
            static ref OBJ: MyStruct = MyStruct {};
        }
        OBJ.doSomething();
    }
    

提交回复
热议问题