liveBook · Manning

Let keyword

As explained in Rust in Action: Systems programming concepts and techniques

A let binding introduces a local Rust variable binding whose associated value may have internally mutable state even when the binding itself is immutable.

In Rust, `let` declares a variable binding. Bindings are immutable by default: `let a = 10;` gives `a` a value without making the binding read-write. A semicolon ends the statement. section 2.2.1

A type can be written after the binding name, as in `let b: i32 = 20;`, or on the integer literal, as in `let c = 30i32;`. An underscore can make the literal easier to read: `30_i32`. A type annotation may be needed when the compiler cannot deduce a unique type. section 2.2.1

Listing 2.2 Adding integers using variables and declaring types
 fn main() {                             #1
   let a = 10;                           #2
   let b: i32 = 20;                      #3
   let c = 30i32;                        #4
   let d = 30_i32;                       #5
   let e = add(add(a, b), add(c, d));
 
   println!("( a + b ) + ( c + d ) = {}", e);
 }
 
 fn add(i: i32, j: i32) -> i32 {         #6
   i + j                                 #7
 }

See several `let` bindings used in a complete program that adds integers. section 2.2.1

An immutable binding does not necessarily mean that all data behind it stays unchanged. Some types have interior mutability: `Rc` and `Arc`, for example, update an internal reference count as references are created and expire. This distinction helps explain why Rust also has `const`. section 3.4.1 section 3.4.1

A related idea is aliasing: multiple references can point to the same memory location. Read-only borrows can alias the same data; a mutable borrow requires exclusive access. section 3.4.1

Mutable bindings

Use `let mut` to declare a mutable binding. For example, `let mut buffer = vec![];` declares a buffer that can be passed as a mutable borrow with `&mut buffer`. section 3.4.1

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains declaration syntax and default immutability, then distinguishes interior mutability and aliasing without detailing their implementations.
Examples
Uses an integer-addition program, reference counts in Rc and Arc, and a mutable buffer passed to a function.
What you can do after
Apply it to declare Rust bindings, annotate integer types, and recognize when an immutable binding can contain changing state.
How it connects
Connects bindings to type annotations, interior mutability, borrowing, aliasing, and constants.

Also explained in

Compare how 2 books explain let keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.