用组合模拟字段继承

问题描述 投票:0回答:2

我有几对结构,其中一个的字段是另一个的完美超集。我想模拟某种继承,这样我就不必为每个结构都有单独的情况,因为这几乎会使我的代码增加一倍。

在像 C 这样的语言中,我可以用这样的东西来模拟字段的继承:

struct A
{
    int a;
};

struct B
{
    struct A parent;
    int b;
};

main()
{
    struct B test1;
    struct A *test2 = &test1;
    test2->a = 7;
}

我想在 Rust 中做这样的事情。我在here读到了类似的内容,但是当我尝试它时,它似乎尚未实现。有没有办法在另一个结构中重用结构中的字段,而无需单独处理案例?

这是我尝试过的枚举语法:

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

链接到一些示例执行。

inheritance struct enums rust composition
2个回答
3
投票

从 Rust 1.22 开始,枚举中公共字段的拟议语法尚未实现。现在唯一的选择是普通的旧构图。如果您希望能够对包含

A
的多种类型进行通用操作,您可以定义一个提供对该
A
访问权限的特征,并在所有这些类型上实现它:

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

0
投票

您可以使用组合有效地模拟继承,并使其透明(无开销),只需使用

Deref

struct A {
    number: usize,
}

struct B {
    a: A
}

impl std::ops::Deref for B {
    type Target = A;

    fn deref(&self) -> &Self::Target {
        &self.a
    }
}

fn main() {
    let b = B {
        a: A {
            number: 42
        }
    };

    println!("{}", b.number);
}

如果您计划拥有

DerefMut
并通过它修改 A 的字段,您还需要
mut B

© www.soinside.com 2019 - 2024. All rights reserved.