Rust Mutability Ownership Demonstration

RustRustBeginner
Practice Now

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

Introduction

In this lab, the mutability of data is demonstrated through Rust programming language by showcasing how ownership and mutability can be changed when a box is moved from an immutable state to a mutable state.

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(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) 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") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") subgraph Lab Skills rust/variable_declarations -.-> lab-99196{{"Rust Mutability Ownership Demonstration"}} rust/mutable_variables -.-> lab-99196{{"Rust Mutability Ownership Demonstration"}} rust/function_syntax -.-> lab-99196{{"Rust Mutability Ownership Demonstration"}} rust/expressions_statements -.-> lab-99196{{"Rust Mutability Ownership Demonstration"}} rust/method_syntax -.-> lab-99196{{"Rust Mutability Ownership Demonstration"}} end

Mutability

Mutability of data can be changed when ownership is transferred.

fn main() {
    let immutable_box = Box::new(5u32);

    println!("immutable_box contains {}", immutable_box);

    // Mutability error
    //*immutable_box = 4;

    // *Move* the box, changing the ownership (and mutability)
    let mut mutable_box = immutable_box;

    println!("mutable_box contains {}", mutable_box);

    // Modify the contents of the box
    *mutable_box = 4;

    println!("mutable_box now contains {}", mutable_box);
}

Summary

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