liveBook · Manning

Assignment

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

Assignment is an operation or expression that binds or updates a variable or other assignable place with a value, potentially transferring ownership when the value is non-copyable.

Rust uses the single equals sign (`=`) as its assignment operator. Assignment binds a name to a value, but it does not produce a Boolean result for a conditional; its result is the unit value, `()`. section 2.2 section 1.6.2

Keep these two operations distinct:

  • Use `=` to assign a value, such as `let a = 10`. section 2.2
  • Use `==` to test equality. Writing `if a = 10` fails because `if` requires a Boolean but receives `()` from the assignment. section 1.6.2
  • When the assigned value owns a non-copyable object, assignment can move ownership to the new variable. section 4.4

Fixing an accidental assignment

This condition is invalid: `if a = 10 { ... }`. Replace the assignment with an equality test: `if a == 10 { println!("a equals ten"); }`. For ownership, `let new_sat_a = sat_a;` transfers the `CubeSat` value to `new_sat_a`; a function can later return it to the original scope. section 1.6.2 section 4.4

1 fn main() {
2     let a = 10;
3 
4     if a = 10 {
5         println!("a equals ten");
6     }
7 }

Inspect the invalid conditional that confuses assignment with equality testing. section 1.6.2

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

How deep it goes
Explains syntax, unit results, compiler diagnostics, conditional misuse, and ownership transfer through concrete Rust programs.
Examples
Uses an invalid `if a = 10` condition, its corrected `a == 10` form, and `CubeSat` ownership transfers.
What it assumes
Assumes familiarity with variables, numbers, and functions while teaching Rust’s unit result and ownership behavior.
What you can do after
Diagnose mistaken assignment in conditions and predict ownership movement when assigning Rust values.
How it connects
Connects assignment with equality comparison, expressions, the unit type, ownership, variables, and function arguments and returns.

Also explained in

Compare how 7 books explain assignment →

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.