2.2 Basic Program Structure

A typical Rust program is composed of several elements:

  • Modules: Organize code into logical units, controlling visibility (public/private).
  • Functions: Define reusable blocks of code.
  • Type Definitions: Create custom data structures using struct, enum, or type aliases (type).
  • Constants and Statics: Define immutable values known at compile time or globally accessible data with a fixed memory location.
  • use Statements: Import items (functions, types, etc.) from other modules or external crates into the current scope.

Rust uses curly braces {} to define code blocks, similar to C. These blocks delimit scopes for functions, loops, conditionals, and other constructs. Variables declared within a block are local to that scope. Crucially, when a variable goes out of scope, Rust automatically calls its “drop” logic, freeing associated memory and releasing resources like file handles or network sockets—a core aspect of Rust’s resource management (RAII - Resource Acquisition Is Initialization).

Unlike C, Rust generally does not require forward declarations for functions or types within the same module; you can call a function defined later in the file. This often encourages a top-down code organization.

Important Exception: Variables must be declared or defined before they are used within a scope.

Items like functions or type definitions can be nested within other items (e.g., helper functions inside another function) where it enhances organization.