Rust Structs, Enums, Match and Box

Structs

  • Complex type defined by the user.
  • Can contain any number of fields of any type.
  • Instantiation: Can be done primitively by instantiating all fields.
  • Field Init Shorthand: Simplifies initialization when field names match variable names.
  • Moving Data: String fields are moved between structs, invalidating the original struct's ownership. Types implementing the Copy trait are copied.
  • Tuple Structs: Useful for naming and differentiating tuples; fields are accessed by index.
  • Struct Methods:
    • Immutable Reference: &self allows methods to access struct data without taking ownership.
    • Mutable Reference: &mut self allows methods to modify the struct.
    • Ownership: self takes ownership of the struct, invalidating the original variable.
  • Static Functions: Often used as constructors, return a new struct instance; Self is an alias for the struct type.

Enumerations

  • Used to represent a value that can be one of a set of possible values.
  • Enum Assignment: Assigning enum variants to variables.
  • Enums with Data: Group data directly with enum variants for cleaner, more consistent states.
  • Custom Enums: Enums can hold multiple data types.
  • Enums Containing Enums: Use Box<T> to store enums on the heap and avoid infinite recursion during compilation.

Box

  • Box<T>: A smart pointer that stores data on the heap with a fixed size, resolving recursive enum size issues.

Option

  • Rust's solution for null checks, indicating the presence (Some(T)) or absence (None) of a value.
  • Defined for any data type.
  • Useful to avoid null-related errors by forcing the user to check for the existence of data.
  • Option API:
    • unwrap(): Extracts value from Some, panics if None.
    • expect("str"): Extracts value from Some, panics with a custom message if None.
    • is_ok(): Returns true if Some.
    • is_none(): Returns true if None.

Match

  • Used for pattern matching on enums.
  • The compiler enforces exhaustive matching, ensuring all enum variants are handled.
  • Catch-All Statements:
    • other: Catches the value from a match statement.
    • _: Matches any value, often used as a default case.
  • Matching with if: Add conditions to match arms.
  • Matching with the if let Statement: Shorthand for a match that only executes code when the value is Some.