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 {
//...
}
}
You can declare an associated constant in an impl:
Rust does not support static fields in structures, so you can't do that. The closest thing you can get is an associated method:
You can't declare a field static in a struct.
You can declare a static variable at module scope like this :
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
, likeMutex
orRWLock
, but these cannot be stored in static variable as they have non-trivial constructors.