9.14 Summary

In this chapter, you learned how to:

  • Define basic structs and understand their similarities and differences compared to C structs.
  • Instantiate structs with or without default values, and handle field initialization.
  • Update structs using struct update syntax while keeping ownership rules in mind.
  • Use tuple structs (fields accessed by index) and unit-like structs (no fields).
  • Add methods and associated functions in impl blocks, using different forms of self (&self, &mut self, and self).
  • Implement getters and setters for finer control over data.
  • Handle ownership of struct fields and incorporate references using lifetimes.
  • Design generic structs to handle multiple types.
  • Compare Rust structs to OOP classes, focusing on Rust’s data and behavior organization without inheritance.
  • Derive or manually implement traits such as Debug, PartialEq, Default, and others.
  • Control visibility by using pub and keeping fields private by default.

By mastering structs, you gain an essential tool in Rust, allowing you to build robust data types and safely manage resources. Next, we’ll explore enums and pattern matching, two powerful features that complement structs and further expand Rust’s expressive power.