In Rust, there's no traditional inheritance, but there are several libraries and patterns to achieve struct extension. Here are the most popular approaches:
1. Using #[derive(Deref)] with derive_more
The derive_more crate provides a clean way to create wrapper structs:
rust
use derive_more::{Deref, DerefMut};
struct BaseStruct {
name: String,
age: u32,
}
#[derive(Deref, DerefMut)]
struct ExtendedStruct {
#[deref]
#[deref_mut]
base: BaseStruct,
extra_field: String,
}
// Usage
let extended = ExtendedStruct {
base: BaseStruct {
name: "Alice".to_string(),
age: 30,
},
extra_field: "extra".to_string(),
};
// Can access base fields directly
println!("{}", extended.name); // Works due to Deref
2. Using struct-ext crate
This crate provides macros specifically for struct extension:
rust
use struct_ext::*;
#[derive(Clone)]
struct Animal {
name: String,
age: u8,
}
#[ext(Animal)]
#[derive(Clone)]
struct Dog {
breed: String,
}
// Usage
let dog = Dog {
name: "Rex".to_string(),
age: 5,
breed: "Labrador".to_string(),
};