1/13
Flashcards covering structs, enums, match statements, and Box<T> in Rust.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
Struct
A complex type defined by the user that can contain any number of fields of any type.
Instantiating a struct
Can be done primitively by instantiating all of its fields.
Tuple Structs
Useful for naming and differentiating one tuple from others, especially when naming each field in a regular struct would be verbose or redundant.
Struct Methods
Functions defined within the context of a struct using 'impl'. They can take '&self' (immutable reference), '&mut self' (mutable reference), or 'self' (ownership) as arguments.
Static Functions in Structs
Often used for constructors that return a new instance of the struct. 'Self' is an alias for the type in the 'impl' block.
Enum
Used for saying a value is one of a possible set of values (enumeration constants).
Enums with data
Group the data right next to the type.
Box
A smart pointer that stores data on the heap, allowing for enums with recursive types to have a known size at compile time.
Option
Rust’s solution for null checks. An enum that holds Some(T) or None, helping the user with checking of possibly non-existent data.
Option API shortcuts
unwrap() extracts the value in Some, crashing if None; expect("str") does the same but prints an error message; isok() returns true if Some; isnone() returns true if None.
Match Statement
Used to compare a value against a series of patterns and execute code based on the matching pattern. Must be exhaustive to avoid errors.
Catch-all statements in Match
'other' catches the value from a match statement. '_' matches the pattern
Matching with if statement
Allows for additional conditions to be checked within a match arm.
If let shorthand
A concise way to run code when a value matches a single pattern, particularly useful with Options.