liveBook · Manning

Scope

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

A scope is a region of program text that determines where names and declarations are visible.

A scope is a region of program text that determines where names and declarations are visible. In Rust, curly-braced code blocks create lexical scopes, including the body of main and function bodies. section 2.2.1

Rust uses scope in several closely related ways:

  • Variable bindings created with let belong to the surrounding block and can be used while that scope makes them available. section 2.2.1
  • Imports can bring traits into local scope, enabling methods such as try_into(); common operations may also arrive through Rust’s implicit prelude. section 2.3.3
  • Scope interacts with ownership and lifetimes: passing an owned value from main into a function moves ownership into that function’s parameter scope. section 4.1.1

A scope boundary in practice

In the CubeSat example, sat_a is created in main and passed to check_status(sat_a). After that call, using sat_a again produces an E0382 error because ownership moved into the function. Rebinding a_status is allowed, but reusing an owned value that has moved is not. section 4.1.1

Figure 4.3 How to interpret the figures in this chapter

Use the figure to trace how scope, control flow, ownership, and lifetimes relate across Rust code. section 4.2

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

How deep it goes
Explains block syntax, local imports, and ownership effects, while deferring a complete treatment of lifetimes and error handling.
Examples
Uses integer bindings, trait imports, and CubeSat function calls to demonstrate scope and ownership behavior.
What it assumes
Builds from zero with Rust variables, functions, blocks, statements, and basic type annotations.
What you can do after
Diagnose why Rust permits or rejects a name, method, or value at a particular point in code.
How it connects
Connects lexical scope with variable bindings, functions, traits, the prelude, ownership, borrowing, and lifetimes.

Also explained in

Compare how 21 books explain scope →

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.