How do I declare a "static" field in a struct in Rust?
28,554
Solution 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 {
//...
}
}
Solution 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);
}
Solution 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.
Related videos on Youtube
Comments
-
Incerteza almost 3 years
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 { //... } }
-
CinCout over 9 yearsusing the
static
keyword doesn't work?
-
-
Incerteza over 9 yearsdo you have any idea why not?
-
Vladimir Matveev over 9 years@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. -
Shepmaster about 6 years
-
aitvann about 6 years@ 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
-
Kristianmitk almost 5 yearsdoc.rust-lang.org/book/const-and-static.html for a working
different things in Rust
link -
jkmartindale almost 5 yearsIf you are looking to make a static variable mutable with
Mutex
you can combine it withlazy-static!
(which does additional wrapping of its own) -
user2284570 over 3 years@Levans, if the struct is declared static, will it apply to its members?
-
user2284570 over 3 years@aitvann if the struct is declared static, will it apply to its members?
-
MisterMiyagi about 3 yearsThis precisely matched my use-case of "constant Python class attribute".
-
SharedRory over 2 yearsThis should be the accepted answer as it does what OP wants
-
CATboardBETA almost 2 yearsI don't think it's "appropriate" for me to flag this saying that a mod should "change" this to accepted answer, given that isn't possible, but I agree. This should be made the accepted answer.