Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Вирази

Програма Rust складається (переважно) з послідовності операторів:

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

У Rust є кілька видів операторів. Найпоширеніші два — це оголошення зв’язування змінної та використання ; із виразом:

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

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

Блоки також є виразами, тож їх можна використовувати як значення в присвоєннях. Останній вираз у блоці буде присвоєно місцю-виразу, такому як локальна змінна. Однак якщо останній вираз блоку закінчується крапкою з комою, повернене значення буде ().

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);
}