Rust Programming Fundamentals: Variable Bindings and Expressions

RustRustBeginner
Practice Now

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

Introduction

In this lab, a Rust program is primarily composed of statements which can include variable bindings and expressions. Statements are designated by a ;, while expressions are followed by a ; and can be used as values in assignments. Additionally, blocks are also considered expressions and can be assigned to local variables, with the last expression serving as the assigned value. However, if the last expression within a block ends with a semicolon, the return value will be ().

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/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/variable_declarations -.-> lab-99302{{"`Rust Programming Fundamentals: Variable Bindings and Expressions`"}} rust/function_syntax -.-> lab-99302{{"`Rust Programming Fundamentals: Variable Bindings and Expressions`"}} rust/expressions_statements -.-> lab-99302{{"`Rust Programming Fundamentals: Variable Bindings and Expressions`"}} end

Expressions

A Rust program is (mostly) made up of a series of statements:

fn main() {
    // statement
    // statement
    // statement
}

There are a few kinds of statements in Rust. The most common two are declaring a variable binding, and using a ; with an expression:

fn main() {
    // variable binding
    let x = 5;

    // expression;
    x;
    x + 1;
    15;
}

Blocks are expressions too, so they can be used as values in assignments. The last expression in the block will be assigned to the place expression such as a local variable. However, if the last expression of the block ends with a semicolon, the return value will be ().

fn main() {
    let x = 5u32;

    let y = {
        let x_squared = x * x;
        let x_cube = x_squared * x;

        // This expression will be assigned to `y`
        x_cube + x_squared + x
    };

    let z = {
        // The semicolon suppresses this expression and `()` is assigned to `z`
        2 * x;
    };

    println!("x is {:?}", x);
    println!("y is {:?}", y);
    println!("z is {:?}", z);
}

Summary

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

Other Rust Tutorials you may like