用组合模拟字段继承 [英] Simulating field inheritence with composition

查看:85
本文介绍了用组合模拟字段继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几对结构,其中一个的字段是另一个的完美超集.我想模拟某种继承,因此不必为每个结构使用单独的大小写,因为这几乎会使我的代码加倍.

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.

在类似C的语言中,我可以使用类似以下内容来模拟字段的继承:

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;
}

我想在Rust中做类似的事情.我读到了类似的内容此处,但是当我尝试过时,它似乎尚未实现.有没有办法在没有单独的案例处理的情况下重用另一个内部结构中的字段?

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
    }
}

这是我的错误:

error: expected one of `(`, `,`, `=`, `{`, or `}`, found `:`
 --> src/main.rs:3:6
  |
3 |     a: i32,
  |      ^ expected one of `(`, `,`, `=`, `{`, or `}` here

链接到一些示例执行.

推荐答案

从Rust 1.22开始,针对枚举中的公共字段的建议语法尚未实现.现在唯一的选择是简单的旧合成.如果您希望能够对包含A的多种类型进行通用操作,则可以定义一个提供对该A访问权限的特征,并在所有这些类型上实现该特征:

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
    }
}

这篇关于用组合模拟字段继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆