9.1 Introduction to Structs and Comparison with C
In Rust, structs allow developers to define custom data types composed of several related values, called fields. While similar to C’s struct
, Rust introduces important distinctions and variations.
The most common form is a struct with named fields:
Rust:
struct Person {
name: String,
age: u8,
}
C:
struct Person {
char* name; // Often a pointer, manual memory management needed
uint8_t age;
};
Key differences and enhancements in Rust include:
- Memory Safety: Rust’s ownership and borrowing rules guarantee memory safety at compile time, preventing issues like use-after-free or data races that can occur with C structs containing pointers. Fields like
String
manage their own memory. - Methods and Behavior: Rust structs can have associated functions and methods defined in separate
impl
blocks. This bundles data and behavior logically, unlike C where functions operating on structs are defined globally or rely on function pointers. - Struct Variants: While named-field structs are common, Rust also offers tuple structs (with unnamed fields accessed by index) and unit-like structs (with no fields at all). These variants serve specific purposes, discussed later.
- No Inheritance: Unlike classes in C++, Rust structs do not support implementation inheritance. Code reuse and polymorphism are achieved through traits and composition.
Rust structs combine the data aggregation capabilities of C structs with enhanced safety, associated behavior, and different structural variants, forming a powerful tool for building complex data structures.