Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a "static" field in a struct in Rust?

Tags:

static

rust

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 {         //...     } } 
like image 536
Incerteza Avatar asked Oct 24 '14 14:10

Incerteza


People also ask

Can you make a struct static?

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.

Does Rust have static variables?

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.

What is static in Rust?

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.

What is the type of struct Rust?

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.


2 Answers

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); } 
like image 57
aitvann Avatar answered Sep 23 '22 19:09

aitvann


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 {         //...         } } 
like image 27
Vladimir Matveev Avatar answered Sep 20 '22 19:09

Vladimir Matveev