Variables and Data Types - Rust

 

Rust Variables: The Good, the Immutable, and the Mutable 

Alright, fellow Rustacean, let's talk about variables—those little containers that hold your precious data. Rust has some unique rules when it comes to variables, and trust me, they're here to keep your code safe and sound. So, grab your favorite beverage, and let's dive in! 

1. Immutable by Default 

In Rust, variables are immutable by default. This means once you assign a value, you can't change it. Try this:

fn main() {
    let name = "Rustacean";
    name = "Not Rustacean"; //  ERROR: Cannot assign twice to immutable variable
    println!("Hello, {}!", name);
}

Boom! Rust yells at you. But why? Because Rust believes in safety first—no accidental changes allowed! 

2. Making Variables Mutable 

If you do want to change a variable, just declare it with mut:

fn main() {
    let mut name = "Rustacean";
    name = "Future Rust Guru";
    println!("Hello, {}!", name);
}

Now Rust is happy, and so is your program! 

Data Types: Rust’s Toolbox of Awesomeness 

Rust is a statically typed language, meaning every variable must have a specific type. But don't worry—Rust is also super smart and can infer types automatically!

1. Integer Types 

Rust provides different integer types, both signed (i) and unsigned (u):

  • i8, i16, i32, i64, i128 (signed)
  • u8, u16, u32, u64, u128 (unsigned)

Example:

fn main() {
    let small: u8 = 255;
    let big: i64 = -99999;
    println!("Small: {}, Big: {}", small, big);
}

2. Floating-Point Numbers 

For decimals, Rust has f32 and f64:

fn main() {
    let pi: f64 = 3.14159;
    println!("Pi is approximately {}", pi);
}

3. Boolean (True or False) 

Boolean values are simple:

fn main() {
    let is_rust_fun: bool = true;
    println!("Is Rust fun? {}", is_rust_fun);
}

4. Characters 

Rust supports Unicode characters, not just ASCII:

fn main() {
    let emoji: char = '🦀';
    println!("Favorite programming language mascot: {}", emoji);
}

5. Strings 

Rust has two types of strings:

  • &str → Immutable string slices (fast & lightweight!)
  • String → Owned, growable heap-allocated string

Example:

fn main() {
    let slice: &str = "Hello";
    let mut full_string: String = String::from("Rust");
    full_string.push_str(" is awesome!");
    println!("{}", full_string);
}

6. Arrays and Tuples 

Arrays (Fixed-size, same type)

fn main() {
    let numbers: [i32; 3] = [1, 2, 3];
    println!("First number: {}", numbers[0]);
}

Tuples (Fixed-size, mixed types)

fn main() {
    let person: (&str, i32) = ("Alice", 30);
    println!("Name: {}, Age: {}", person.0, person.1);
}

Wrapping Up 

Rust's variable rules and data types might seem strict at first, but they help prevent bugs and make your code more reliable. Now that you’ve got a solid grasp of Rust variables and data types, go forth and write some awesome Rust code!

Post a Comment

0 Comments