How do I declare a "static" field in a struct in Rust?

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 {
        //...    
    }
}

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.


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);
}

Tags:

Rust