2.2 Program Structure
A Rust program typically consists of:
- Modules: Grouping related items (functions, structs, traits, etc.).
- Functions: Reusable units of code.
- Type Definitions: Structs, enums, type aliases.
- Constants and Statics: Immutable or fixed-location data.
use
Statements: Bringing external names into scope.
Like C, Rust uses {}
to define code blocks. These blocks appear in various constructs, such as function bodies, loop bodies, and if
statement branches. Blocks can be nested, and each one introduces a new scope. Any types, functions, or variables declared within a block are considered local, meaning they are not accessible outside of that scope. In Rust, all local variables are automatically dropped when their scope ends, releasing memory and closing associated resources, such as files or network connections.
Unlike C, Rust does not require forward declarations for functions: you can freely call functions defined later in the file. This encourages a top-down design, where higher-level functions appear near the top, and detailed helpers follow below.
Important Exception: Variables must be declared before use.
Nesting: You can nest items in Rust where it makes sense (for example, define helper functions or constants inside other functions or modules).