我想将此代码转换为Rust
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以这就是我尝试过的:
Direction d1 = Direction.EAST;
Direction d2 = Direction.SOUTH;
Run Code Online (Sandbox Code Playgroud)
然后我被困住了.接下来我该怎么办?
小智 11
这是你的Java枚举的样子:
+-----+-----+
| tid | 0 |
+-----+-----+
+-----+-----+
| tid | 90 |
+-----+-----+
+-----+-----+
| tid | 180 |
+-----+-----+
+-----+-----+
| tid | 270 |
+-----+-----+
Run Code Online (Sandbox Code Playgroud)
tid对于所有四个方向都是相同的,并确定类型Direction及其方法.以下是如何使用您的锈代码East(0),Noth(90),West(180),South(270)如下所示:
+-------+-----+-----+-----+-----+
| East | 0 | | | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| North | | 90 | | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| West | | | 180 | |
+-------+-----+-----+-----+-----+
+-------+-----+-----+-----+-----+
| South | | | | 270 |
+-------+-----+-----+-----+-----+
Run Code Online (Sandbox Code Playgroud)
每个构造函数都有一组字段(在本例中为int每个字段),它们是不同的.实际上,由于任何给定Direction的最多East/North/East/West只有一个,因此在任何时间点只使用一组字段并且它们使用相同的存储器(因此Direction实际上只占用两个字).
但从概念上讲,上述内容是准确的,并说明了Rust版本的两个问题.首先,存在重复:构造函数标记(N/E/S/W)对于所有四个都已经不同,因此int字段是多余的.其次,概念上int的North是来自不同int的South,即使它有正好为所有这些相同的含义.此外,没有什么能阻止人们创造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,
}
}
}
Run Code Online (Sandbox Code Playgroud)
方向隐含在枚举标记中,并用get_angle.
Vla*_*eev 10
德尔南的答案是绝对正确的,你可能应该采用它,但还有另一种方法.Rust枚举也可以与C枚举类似,其中枚举常量本质上是数值常量.Rust允许你写这样的东西:
enum Direction {
East = 0,
North = 90,
West = 180,
South = 270
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将枚举值用作具有显式强制转换的数字:
let value = South as uint;
println!("{}", value); // prints 270
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为枚举本质上是带有隐藏鉴别字段的结构,这是一个数字.因此,没有带参数的变体的枚举值仅包含该鉴别符字段.它的值可以通过数字转换访问,您可以在枚举定义中为不同的枚举变量设置具体值.
我的意思是,这只有在需要整数时才有效.你不能用这种方式获得字符串或浮点数,就像你可以用Java做的那样(其中枚举变体只是具有任意字段的常规对象).如果你需要它,你将不得不使用单独的getter方法,就像在delnan的答案中一样.
| 归档时间: |
|
| 查看次数: |
2021 次 |
| 最近记录: |