How do I declare a “static” field in a struct in R

2019-06-15 01:15发布

问题:

How do I declare a "static" field in a struct in Rust, preferably with a default value:

struct MyStruct {
    x: i32,               // instance
    y: i32,               // instance
    my_static: i32 = 123, // static, how?
}

fn main() {
    let a = get_value();
    if a == MyStruct::my_static {
        //...
    } else {
        //...
    }
}

回答1:

Rust does not support static fields in structures, so you can't do that. The closest thing you can get is an associated method:

struct MyStruct {
    x: i32,
    y: i32,
}

impl MyStruct {
    #[inline]
    pub fn my_static() -> i32 {
        123
    }
}

fn main() {
    let a = get_value();
    if a == MyStruct::my_static() {
        //...
    } else {
        //...    
    }
}


回答2:

You can declare an associated constant in an impl:

struct MyStruct {
    x: i32,
    y: i32,
}

impl MyStruct {
    const MY_STATIC: i32 = 123;
}

fn main() {
    println!("MyStruct::MY_STATIC = {}", MyStruct::MY_STATIC);
}


回答3:

You can't declare a field static in a struct.

You can declare a static variable at module scope like this :

static FOO: int = 42;

And you can't have a static variable mutable without unsafe code : to follow borrowing rules it would have to be wrapped in a container making runtime borrowing checks and being Sync, like Mutex or RWLock, but these cannot be stored in static variable as they have non-trivial constructors.



标签: rust