Variables in Rust

In Rust, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

fn main() {
    // let declares 1 or more variables.
    let a = "initial";
    println!("{}", a);

    // You can declare multiple variables at once.
    let (b, c): (i32, i32) = (1, 2);
    println!("{} {}", b, c);

    // Rust will infer the type of initialized variables.
    let d = true;
    println!("{}", d);

    // Variables declared without a corresponding
    // initialization are not allowed in Rust.
    // Instead, we need to specify a type and initialize it:
    let e: i32 = 0;
    println!("{}", e);

    // In Rust, we use let for both declaration and initialization.
    // Variables are immutable by default.
    let f = "apple";
    println!("{}", f);
}

To run the program:

$ rustc variables.rs
$ ./variables
initial
1 2
true
0
apple

In Rust:

  1. Variables are immutable by default. To make a variable mutable, use let mut.
  2. Type inference is available, but you can also explicitly specify types.
  3. There’s no direct equivalent to Go’s := syntax, as let is used for both declaration and initialization.
  4. Rust doesn’t allow uninitialized variables, so we always need to provide an initial value or use the Option type.
  5. Multiple variable declaration is done using tuples.

These differences reflect Rust’s focus on safety and preventing common programming errors at compile time.