rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

lazy_static inside function would be different instance #157

Closed atenjin closed 4 years ago

atenjin commented 4 years ago

for example: lazy_static: v1.4.0

fn main() {
    fn a() {
        lazy_static::lazy_static! {
            pub static ref CACHE: std::sync::Mutex<u32> = std::sync::Mutex::new(1);
        }
        let mut m = CACHE.lock().unwrap();
        *m = 2;
        println!("a cache:{:p}", &m);
    }
    fn b() {
        lazy_static::lazy_static! {
            pub static ref CACHE: std::sync::Mutex<i32> = std::sync::Mutex::new(-1);
        }
        let mut m = CACHE.lock().unwrap();
        *m= -2;
        println!("b cache:{:p}", &m);
        a();
    }
    a();
    b();
}

the result is:

a cache:0x7ffc24ff22e8
b cache:0x7ffc24ff22e8
a cache:0x7ffc24ff2228

like this example, there is a static variable inside function a, and another static variable inside function b, then, function b would call a in the end.

In my expect, the static variable inside b should be same instance, but in result, the point address is a same as b, but in different call, the static variable inside b is different instance.

I'm confuse with this.

In normal case:

    fn eee() {
        static I: i32= 1;
        println!("eee I:{:p}", &I);
    }
    fn www() {
        static W: u32 = 10;
        println!("www W:{:p}", &W);
        eee();
    }
    eee();
    www();

the result is :

eee I:0x555bed634254
www W:0x555bed634260
eee I:0x555bed634254

this is what in my expect.

atenjin commented 4 years ago

my fault

BurntSushi commented 4 years ago

Can you say more about why you closed this, in case your resolution helps others?