liveBook · Manning

Binding

As explained in Learn Rust in a Month of Lunches

A variable is a named program binding that refers to a value and may permit reassignment according to its declaration.

A binding gives a name to a value so the program can use that value later. In Rust, let creates a binding such as my_number for 8. The name helps you remember what the data represents. section 1.7 section 1.2

A Rust binding follows a few practical rules:

  • Its lifetime is limited to the surrounding code block, or scope. A binding created inside a nested block cannot be used after that block ends. section 1.6 section 1.7
  • A block can return a value, allowing an outer binding to receive the result even though the inner binding disappears. section 1.7
  • Bindings are immutable unless declared with mut. Shadowing instead creates another binding with the same name. section 1.12
  • Rust often infers a binding's type, though you can provide the type name explicitly. section 1.0 section 1.12

A binding from a block

let my_number = { let second_number = 8; second_number + 9 }; println!("My number is: {}", my_number); section 1.7

fn main() {
    {
        let my_number = 8;                      #1
    }
    println!("Hello, number {}", my_number);    #2
}

Compare the nested binding's scope with the later use of my_number; the compiler rejects a name after its block has ended. section 1.7

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains declaration, type inference, scope, block results, mutability, and shadowing, without descending into compiler or memory internals.
Examples
Uses named numbers, color strings, formatted println! output, nested blocks, returned block values, and scope errors.
What it assumes
Assumes only basic Rust syntax and introduces let, code blocks, scope, mut, type inference, and shadowing from the beginning.
What you can do after
Build it from scratch by declaring Rust bindings, using them in output, controlling mutability, and returning values from blocks.
How it connects
Connects bindings with type inference, code blocks, scope, mutability, shadowing, functions, and formatted output.

Also explained in

Compare how 11 books explain binding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.