Static Variables (`static`) in Rust 🎯

beginner
14 min

Static Variables (static) in Rust 🎯

Welcome to another engaging and educational tutorial on CodeYourCraft! Today, we're diving into the fascinating world of Static Variables in Rust. Let's get started!

What are Static Variables? 📝

Static variables are variables that exist for the lifetime of the program, rather than the lifetime of the current scope. In other words, they persist even after the function or block they're defined in has completed execution.

Why Use Static Variables? 💡

Static variables are useful when you need to store data that needs to persist for the entire program lifecycle. For example, you might want to keep a counter of the number of times a function has been called, or maintain a cache of frequently accessed data.

Defining a Static Variable 🎯

To define a static variable, simply prefix the variable name with the static keyword, like so:

rust
static MY_STATIC_VAR: u32 = 42;

In the example above, MY_STATIC_VAR is a static variable of type u32 (unsigned 32-bit integer) with the initial value 42.

Accessing a Static Variable 🎯

To access a static variable, you use the :: syntax. For example:

rust
println!("The value of MY_STATIC_VAR is: {}", super::MY_STATIC_VAR);

In the example above, we're accessing the static variable MY_STATIC_VAR defined in the same module (indicated by super::) and printing its value.

Static Variables and Thread Safety 📝

Static variables in Rust are thread-local by default, which means that they can only be accessed from the thread in which they were created. This is important for maintaining the integrity of your data when working with multiple threads.

However, if you need a static variable to be shared across all threads, you can use the static keyword along with the sync trait:

rust
static MY_STATIC_VAR: std::sync::Arc<std::sync::Mutex<u32>> = std::sync::Arc::new(std::sync::Mutex::new(42));

In this example, MY_STATIC_VAR is a shared, mutable static variable wrapped in a std::sync::Mutex for thread safety.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What keyword is used to define a static variable in Rust?

Practical Example 🎯

Let's create a simple counter using a static variable:

rust
static COUNTER: std::sync::Arc<std::sync::Mutex<u32>> = std::sync::Arc::new(std::sync::Mutex::new(0)); fn increment_counter() { let mut num = COUNTER.lock().expect("Failed to lock counter"); *num += 1; } fn main() { for _ in 0..10 { thread::spawn(|| { for i in 0..100 { increment_counter(); } }); } let counter = COUNTER.lock().expect("Failed to lock counter"); println!("Total count: {}", counter); }

In this example, we're creating a shared counter using a static variable and multiple threads. The increment_counter function increments the counter, and the main function spins up 10 threads, each of which increments the counter 100 times. Finally, we print the total count.

And that's it for today! With this lesson, you now have a solid understanding of static variables in Rust. Keep exploring and coding! 🚀