gpt4 book ai didi

Rust 中具有结构的枚举

转载 作者:行者123 更新时间:2023-11-29 08:01:24 24 4
gpt4 key购买 nike

我现有的 Java 实现必须重写为 Rust。

Java代码

enum Direction {
EAST(0), WEST(180), NORTH(90), SOUTH(270);

private Direction(final int angle) {
this.angle = angle;
}

private int angle;

public int getAngle() {
return angle;
}
}

Java代码使用示例

Direction d1 = Direction.EAST;
Direction d2 = Direction.SOUTH;

Rust 代码

所以这是我尝试过的:

enum Direction {
East(u32),
West(u32),
North(u32),
South(u32);
}

impl Direction {
// ???
fn new() -> Direction // incorrect
}

然后我卡住了。接下来我该做什么?

最佳答案

这是您的 Java 枚举的样子:

+-----+-----+
| tid | 0 |
+-----+-----+
+-----+-----+
| tid | 90 |
+-----+-----+
+-----+-----+
| tid | 180 |
+-----+-----+
+-----+-----+
| tid | 270 |
+-----+-----+

tid 对于所有四个方向都是相同的,并标识类型 Direction 及其方法。以下是如何使用您的 Rust 代码,East(0)Noth(90)West(180)South(270 ) 看起来像:

+-------+-----+-----+-----+-----+
| East | 0 | | | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| North | | 90 | | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| West | | | 180 | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| South | | | | 270 |
+-------+-----+-----+-----+-----+

每个构造函数都有一组不同的字段(在本例中,每个字段一个int)。实际上,由于任何给定的 Direction 至多是 East/North/East/West 之一,因此在任何时间点都只使用一组字段,并且它们使用相同的内存(所以 Direction 实际上只占两个字)。

但从概念上讲,以上内容是准确的,并且说明了您的 Rust 版本存在的两个问题。首先,存在重复:所有四个的构造函数标记 (N/E/S/W) 已经不同,因此 int 字段是多余的。其次,从概念上讲,North 中的 intSouth 中的 int 不同,尽管它们具有完全相同的功能对他们所有人都意味着。此外,没有什么能阻止人们创建 North(214)East(180)

最直接的翻译是这样的:

enum Direction { North, East, South, West }

impl Direction {
fn get_angle(self) -> int {
match self {
East => 0,
West => 180,
North => 90,
South => 270,
}
}
}

方向隐含在枚举标签中,并使用 get_angle 提取。

关于Rust 中具有结构的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com