5.11 Summary

This chapter covered the foundational building blocks common to many programming languages, as implemented in Rust, highlighting key differences from C:

  • Keywords: Reserved words defining Rust’s syntax, including raw identifiers (r#) for conflicts.
  • Identifiers: Naming rules (Unicode-based) and conventions (snake_case, UpperCamelCase).
  • Expressions vs. Statements: Expressions evaluate to a value; statements perform actions and end with ;. Block expressions ({}) are a key feature. Assignment is a statement.
  • Data Types:
    • Scalar: Integers (i32, u8, usize, etc.), floats (f64, f32), booleans (bool), characters (char - 4 bytes Unicode).
    • Compound: Tuples (fixed-size, heterogeneous (T1, T2)), Arrays (fixed-size, homogeneous [T; N]).
  • Variables: Declared with let, immutable by default, made mutable with mut. Rust enforces initialization before use. The term “binding” is common but can be thought of as declaration/initialization for simple cases.
  • Constants (const): Compile-time values, inlined, no fixed address.
  • Statics (static): Program lifetime, fixed memory address, static mut requires unsafe and is discouraged.
  • Shadowing: Re-declaring a variable name with let, creating a new variable.
  • Operators: Familiar arithmetic, comparison, logical, bitwise operators. No ++/--, no ternary ?:, requires strict type matching (use as for casts).
  • Numeric Literals: Syntax for integers (various bases, suffixes, _ separators), floats (suffixes, _, exponents), byte literals (b'A').
  • Overflow: Well-defined behavior: debug builds panic, release builds wrap (integers). Explicit handling methods (checked_, wrapping_, etc.) available for consistent control. Floats use Infinity/NaN.
  • Performance: Considerations for different numeric types (i32/f64 often good defaults).
  • Comments: Regular (//, /* */) and documentation (///, //!) comments for explanation and rustdoc generation.

These concepts provide a necessary base for writing Rust programs. While some aspects resemble C, Rust’s emphasis on explicitness (like type casting and overflow handling), static guarantees (like initialization checks), and default immutability contribute significantly to its safety and reliability. The next chapters will delve into Rust’s unique ownership and borrowing system, showing how it interacts with functions, control flow, and data structures to provide memory safety without a garbage collector.