CodeToLive

Variables and Data Types in Rust

In Rust, variables are immutable by default, meaning their values cannot be changed after assignment. You can make a variable mutable using the mut keyword.

Declaring Variables

Variables in Rust are declared using the let keyword.


let x = 10;  // Immutable variable
let mut y = 20;  // Mutable variable
y = 30;  // Valid because y is mutable
      

Variable Scope and Shadowing

Variables in Rust are block-scoped. You can also shadow a variable by declaring a new variable with the same name.


fn main() {
    let x = 5;
    {
        let x = x * 2;  // Shadowing the outer x
        println!("Inner x: {}", x);  // Prints 10
    }
    println!("Outer x: {}", x);  // Prints 5
}
      

Constants

Constants are declared using the const keyword and must have a type annotation.


const MAX_POINTS: u32 = 100_000;
println!("Max points: {}", MAX_POINTS);
      

Type Inference

Rust can infer the type of a variable based on its value.


let x = 5;  // Rust infers x as i32
let y = 3.14;  // Rust infers y as f64
      

Common Data Types

Compound Data Types

Rust supports compound data types like tuples and arrays.


// Tuple
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;  // Destructuring
println!("x: {}, y: {}, z: {}", x, y, z);

// Array
let arr = [1, 2, 3, 4, 5];
println!("First element: {}", arr[0]);
      

Interactive Code Examples

Try running these examples in your Rust environment to see how they work!


// Interactive Example
fn main() {
    let name = "Alice";
    let age = 25;
    println!("Name: {}, Age: {}", name, age);
}
      

Practice Problems

Test your understanding with these practice problems:

  1. Write a Rust program to swap the values of two variables.
  2. Write a Rust program to calculate the area of a rectangle using a tuple.
  3. Write a Rust program to find the largest number in an array.
Next: Control Structures