I am porting some code from C++ to Rust, and I'm unsure as to what the equivalent way to handle common base class members in C++ is in idiomatic Rust. An example of what I have in C++:
class Base {
public:
Base(int n) : n_(n) {}
virtual int foo() = 0;
int n_;
};
class D1 : public Base {
public:
D1(int n) : Base(n) {}
virtual int foo() {/* return something to do with n_ */}
};
class D2 : public Base {
public:
D1(int n) : Base(n) {}
virtual int foo() {/* return some other thing to do with n_ */}
};
In C++, I can define n_
once in the base class constructor, and I can use it from any of the derived classes.
My Rust structs currently look like this:
struct D1 {
n_: i32,
}
struct D2 {
n_: i32,
}
trait Base {
fn foo(&self) -> i32;
}
impl D1 {
fn new(n: i32) -> Self {
D1 { n_: n }
}
}
impl D2 {
fn new(n: i32) -> Self {
D2 { n_: n }
}
}
impl Base for D1 {
fn foo(&self) -> i32 {
// Contrived example to show D1 and D2 have different uses of n_
self.n_
}
}
impl Base for D2 {
fn foo(&self) -> i32 {
// Contrived example to show D1 and D2 have different uses of n_
self.n_ * 2
}
}
This feels like more code duplication than I'm used to. Is there a way to have an n_
data member declared only once for both structs?