MIR and borrow checking
Quick answer
Mid-level IR (MIR) represents function execution with explicit control flow and simpler operations. rustc uses it to reason about moves, initialization, borrowing and later transformations.
Track uses across control flow
Basic blocks contain statements and end in a terminator. Borrow checking uses flow-sensitive information and region inference; a shared borrow can end after its last relevant use instead of at the closing brace. Moves invalidate use of a moved non-Copy value until reinitialization. Drop elaboration and optimization also use intermediate representations. MIR text is for inspection, not a stable API.
fn main() { let mut s = String::from("a"); let view = &s; println!("{view}"); s.push('b'); println!("{s}");}Expected stdout (not executed):
aabThe shared reference is no longer needed when push mutates the string.
# Save the previous example as sample.rs in a scratch directory.rustc +1.85.0 --edition=2024 --emit=mir sample.rsManual terminal step; not executed. Expected behavior (environment dependent):
A sample.mir file if the compiler and input are available.Inspect blocks and calls; do not assume particular temporary names or block numbering.
Common mistake
Do not assume last-use reasoning allows a mutation when the shared reference is used again afterwards.
Try it yourself
Move the first println after push and explain why the new order should be rejected.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
MIR and borrow checking — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A shared borrow is last used before a mutation of its owner. What allows the compiler to accept that sequence?
MIR and borrow checking — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut s = String::from("a"); let view = &s; println!("{view}"); s.push('b'); println!("{s}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
MIR and borrow checking — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```bash # Save the previous example as sample.rs in a scratch directory. rustc +1.85.0 --edition=2024 --emit=mir sample.rs ``` Which outcome or interpretation best matches this example?