【发布时间】:2017-12-12 01:28:05
【问题描述】:
我有几对结构,其中一个的字段是另一个的完美超集。我想模拟某种继承,这样我就不必为每个结构设置单独的案例,因为这几乎会使我的代码翻倍。
在像 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
Link 执行一些示例。
【问题讨论】:
-
“当我尝试过时,它似乎还没有实现”愿意分享你的尝试吗?你遇到的错误?把它放在play.rust-lang.org 上,这样其他人也可以运行它。
标签: inheritance struct enums rust composition