Static fields in a structure in Rust

How to declare a β€œstatic” field in a structure in Rust, preferably with a default value:

struct MyStruct { x: int, //instance y: int, //instance my_static: int = 123 //static, how? } //using let a = get_value() if a == MyStruct::my_static { ... } else {...} 
+6
source share
3 answers

Rust does not support a static field in structures, so you cannot do this. The closest you can get are static methods:

 impl MyStruct { #[inline] pub fn my_static() -> int { 123 } } if a == MyStruct::my_static() { ... } else { ... } 
+5
source

You cannot declare a static field in a structure.

You can declare a static variable in the module scope as follows:

 static FOO: int = 42; 

And you cannot change a static variable without unsafe code: in order to follow the borrowing rules, you would have to wrap them in a container in order to perform earnings checks at runtime and be Sync , for example Mutex or RWLock , but they cannot be stored in a static variable, since they have non-trivial constructors.

+3
source

You can declare a related constant in impl:

 struct MyStruct { x: i32, y: i32, } impl MyStruct { const MY_STATIC: i32 = 123; } fn main() { println!("MuStruct::MY_STATIC = {}", MuStruct::MY_STATIC); } 
-1
source

Source: https://habr.com/ru/post/977182/


All Articles