Static variables in rust can have a destructor but that destructor is never run as they have a static lifetime. This means that they never run out of scope in the entire lifetime of the program in which they are declared.
Note if a variable is declared as static inside a function, the scope, meaning the accessibility of the variable is not affected. Hence, parts of the program outside the function cannot access its value. However, its scope is not dropped when the function scope dies.
To learn more about drop and destructors in Rust, check our tutorial on Rust Destructors.
Points to Note
The following are some important points to note when using static variables in Rust:
Static variables must be thread safe. Hence, the specified type must implement the sync trait. Setting a variable as static with a type that is not thread safe may lead to data race conditions.
Static variables can only refer other static variables by reference only.
Constants or Static
Although static variables are not a substitution for constant variables, Rust recommends to always favor constants first unless:
- You need to store large amounts of data.
- You require interior mutability
- You require single-address nature of static variables.
Rust Create Static Variable
There are two main ways to create a static variable in Rust. The first is to create a constant value with a static declaration.
An example code is as shown below:
The second method to create a static value is to create a string literal with type &’static str. Example is as shown:
Keep in mind that the str type in Rust is a type of string literals defined as &’static str.
Since string literals are slices of a string, they are stored in the final binary and hence, a static lifetime.
Since String types in Rust might not live in the lifetime of the program, it is not possible to convert a String type to a static string. However, you can create a string slice which is static as show in the example below:
let str_slice: &str = &string[..];
}
NOTE: Although you can have a mutable static value, Rust cannot prove dangling references or data races when accessing a mutable static variable. Rust generally discourages using static mutable variables.
Conclusion
This short article attempts to discuss the concept of static variables in the Rust. Keep in mind that this guide cannot serve as a reference to statics in Rust. Check the documentation to understand how static works in Rust.