HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustModerate

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
structhowfielddeclareruststatic

Problem

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

Solution

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

Code Snippets

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

Context

Stack Overflow Q#26549480, score: 23

Revisions (0)

No revisions yet.