70

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

3 Answers 3

119

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

static and const are different things in Rust.
@ Shepmaster, I know. I think the author of the question had in mind not static which is in Rust, but a member of the structure that is not stored in the object of the structure
doc.rust-lang.org/book/const-and-static.html for a working different things in Rust link
@aitvann if the struct is declared static, will it apply to its members?
This precisely matched my use-case of "constant Python class attribute".
23

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

3 Comments

do you have any idea why not?
@AlexanderSupertramp, probably because they are not really needed? Static fields can only used for scoping and encapsulation, but encapsulation unit in Rust is module, so just make a static in the module your struct is in, that's it.
You should use an associated constant on the impl instead of a function. It solves their issue.
12

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.

3 Comments

If you are looking to make a static variable mutable with Mutex you can combine it with lazy-static! (which does additional wrapping of its own)
@Levans, if the struct is declared static, will it apply to its members?
They meant static like in other languages, not a static variable in Rust. An associated constant solves their issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.