Search code examples
rustinstantiation

Does Rust have an elegant way to manipulate values further when assigning a value from a block statement?


I am trying to declare a variable with expressions in a block.

let y = {
    let x = 3;
    x + 1
};

The code below equals 4. As I understand, the last element in the block cannot have a semicolon as that makes this expression a statement.

What if I want to manipulate the values further? For instance, what if I want to instantiate two variables and multiply them? Does Rust have an elegant way to handle this, or do I need to split this into many expressions?

Pseudocode:

//An attempt to multiply two instantiated values in a block
let y = {
    let z = 2;
    let x = 3;
    x + 1;
    x * z
};

Solution

  • The issue with the pseudocode is that x is immutable — it cannot be changed. To achieve the desired effect, you must make x mutable and it can be increased with x += 1, not x + 1:

    let y = {
        let z = 2;
        let mut x = 3;
        x += 1;
        x * z
    };
    

    will return 8.