Simulating field inheritence with composition

陌路散爱 提交于 2021-02-17 05:04:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!