9.13 Summary
This chapter covered Rust structs, highlighting their similarities and differences compared to C structs. We explored data organization, behavior association, memory safety, and performance aspects.
Key takeaways include:
- Structs group named fields; variants include tuple and unit structs.
- Instances are created using struct literals; access fields via dot notation.
- Operations like assignment and comparison are typically enabled by derived traits (
Copy
,PartialEq
). Printing usesDebug
orDisplay
. - Destructuring extracts fields, potentially moving non-
Copy
data out. - Ownership dictates how structs and their fields are managed (drop, move, copy). Lifetimes ensure safety for borrowed fields.
- Methods (
impl
blocks) associate behavior (&self
,&mut self
,self
). - Generics create reusable struct definitions; trait bounds constrain them.
- Memory layout is optimized by default;
#[repr(C)]
ensures C compatibility. - Visibility (
pub
) controls encapsulation at the module level.
Structs are foundational in Rust for creating custom, safe, and efficient data types.