问题
I have several pairs of structs for which the fields of one is a perfect superset of the other. I'd like to simulate some kind of inheritance so I don't have to have separate cases for each struct since that would almost double my code.
In a language like C, I could simulate inheritance of fields with something like this:
struct A
{
int a;
};
struct B
{
struct A parent;
int b;
};
main()
{
struct B test1;
struct A *test2 = &test1;
test2->a = 7;
}
I want to do something like this in Rust. I read about something like that here but when I tried it, it doesn't seem to have been implemented yet. Is there any way to do reuse the fields in a struct inside another without separate case handling?
Here is the enum syntax I tried:
enum Top
{
a: i32,
A {},
B {
b: i32
}
}
And this is my error:
error: expected one of `(`, `,`, `=`, `{`, or `}`, found `:`
--> src/main.rs:3:6
|
3 | a: i32,
| ^ expected one of `(`, `,`, `=`, `{`, or `}` here
Link to some sample execution.
回答1:
The proposed syntax for common fields in enums hasn't been implemented as of Rust 1.22. The only option right now is plain old composition. If you want to be able to operate generically on multiple types that contain an A
, you may be able to define a trait that provides access to that A
and implement it on all of those types:
trait HaveA {
fn a(&self) -> &A;
fn a_mut(&mut self) -> &mut A;
}
impl HaveA for B {
fn a(&self) -> &A {
&self.parent
}
fn a_mut(&mut self) -> &mut A {
&mut self.parent
}
}
来源:https://stackoverflow.com/questions/47764050/simulating-field-inheritence-with-composition