Mutable Variable Bindings in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn about mutability in Rust and how variable bindings can be made mutable using the mut modifier. The lab includes an example of declaring immutable and mutable bindings, demonstrating how a mutable binding can be modified, and highlighting the error when trying to assign a new value to an immutable variable.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/variable_declarations -.-> lab-99291{{"`Mutable Variable Bindings in Rust`"}} rust/mutable_variables -.-> lab-99291{{"`Mutable Variable Bindings in Rust`"}} rust/function_syntax -.-> lab-99291{{"`Mutable Variable Bindings in Rust`"}} rust/expressions_statements -.-> lab-99291{{"`Mutable Variable Bindings in Rust`"}} end

Mutability

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

fn main() {
    let _immutable_binding = 1;
    let mut mutable_binding = 1;

    println!("Before mutation: {}", mutable_binding);

    // Ok
    mutable_binding += 1;

    println!("After mutation: {}", mutable_binding);

    // Error! Cannot assign a new value to an immutable variable
    _immutable_binding += 1;
}

The compiler will throw a detailed diagnostic about mutability errors.

Summary

Congratulations! You have completed the Mutability lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like