Emulating OO inheritance
⚓ Rust 📅 2026-05-03 👤 surdeus 👁️ 3I have an application that depends on items of different types having both common methods and special methods for item-specific data. Although not overly pretty, it actually works.
However, the counterpart having common methods and common data became a real mess with unsafe pointers and duplicated code. So my question is simply: is there a reasonable way to do this in Rust?
// Rust does not support inheritance, how to proceed?
struct AContent {
// Item-specific data supporting both common and specific methods. SOLVED
// Common data used by common methods. UNRESOLVED
common_data: bool // Just an example
}
struct BContent {
// Item-specific data supporting both common and specific methods. SOLVED
// Common data used by common methods. UNRESOLVED
common_data: bool // Just an example
}
enum Item {
A(AContent),
B(BContent)
}
impl Item {
fn set_common_data(&self, data: bool) -> Item {
todo!();
*self // for "chaining" purposes
}
fn get_common_data(&self) -> bool {
todo!()
}
}
fn main() {
let a = Item::A(AContent{common_data: false});
let b = Item::B(BContent{common_data: false});
// Whish:
a.set_common_data(true).get_common_data();
b.get_common_data();
}
Note the *self, it is the counterpart to return this in Java and JavaScript.
1 post - 1 participant
🏷️ Rust_feed