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 { //... } }
A structure declaration cannot be declared static, but its instancies can. You cannot have static members inside a structure because the members of a structure inherist the storage class of the containing struct. So if a structure is declared to be static all members are static even included substructures.
Static variables can be mutable. Since Rust can't prove the absence of data races when accessing a static mutable variable, accessing it is unsafe.
A static item is similar to a constant, except that it represents a precise memory location in the program. A static is never "inlined" at the usage site, and all references to it refer to the same memory location. Static items have the static lifetime, which outlives all other lifetimes in a Rust program.
Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit structs. Regular structs are the most commonly used. Each field defined within them has a name and a type, and once defined can be accessed using example_struct.
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); }
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 { //... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With