» Quick Introduction to Rust » 1. Basics » 1.5 Variables

Variables

Mutability

Variable bindings are immutable by default, but this can be overriden using the mut modifier.

// immutable by default
let a = 1;
// Error! Cannot assign a new value to an immutable variable
a += 1;

// mutable variable
let mut b = 1;
// OK
b += 1;

Scope

Variable bindings have a scope, and their lifetime is limited to the block where they are bound.

fn main() {
    // This binding lives in the main function
    let long_lived_binding = 1;

    // This is a block, and has a smaller scope than the main function
    {
        // This binding only exists in this block
        let short_lived_binding = 2;

        println!("inner short: {}", short_lived_binding);
    }
    // End of the block

    // Error! `short_lived_binding` doesn't exist in this scope
    println!("outer short: {}", short_lived_binding);

    // OK
    println!("outer long: {}", long_lived_binding);
}

Shadowing

Variable shadowing is allowed in Rust.

fn main() {
    let a = 1;
    {
        println!("before being shadowed: {}", a); // before being shadowed: 1

        // This binding *shadows* the outer one
        let a = "abc";

        println!("shadowed in inner block: {}", a); // shadowed in inner block: abc
    }
    println!("outside inner block: {}", a); // outside inner block: 1

    // This binding *shadows* the previous binding
    let a = 2;
    println!("shadowed in outer block: {}", a); // shadowed in outer block: 2
}

Code Challenge

Try to modify the code provided in the editor to fix the is_palindrome function.

Loading...
> code result goes here
Prev
Next