我如何“切换"通过枚举变体? [英] How do I "toggle" through enum variants?
问题描述
我想编写一个函数,将提供的值切换/切换到枚举中的下一个值,并在末尾回绕:
I'd like to write a function which toggles/switches the provided value to the next in the enum and wraps around at the end:
enum Direction { NORTH, SOUTH, EAST, WEST }
例如,NORTH
=> SOUTH
, SOUTH
=> EAST
, EAST
=> WEST
, WEST
=> NORTH
.
For example, NORTH
=> SOUTH
, SOUTH
=> EAST
, EAST
=> WEST
, WEST
=> NORTH
.
use Direction::*;
static DIRECTIONS: [Direction; 4] = [NORTH, SOUTH, EAST, WEST];
枚举不是应该被枚举"的吗?我依稀记得之前在 Rust 中看到过一个例子,但我似乎找不到它.由于 Rust 枚举更像是联合/变体,我想这会使事情复杂化.
Aren't enums suppose to be "enumerated"? I vaguely remember seeing an example before in Rust, but I can't seem to find it. Since Rust enums are more like unions/variants, I guess this complicates things.
推荐答案
我想这样的事情可以解决问题:
I guess something like this will do the trick:
#[macro_use]
extern crate num_derive;
extern crate num_traits;
use num_traits::FromPrimitive;
#[derive(Debug, Copy, Clone, FromPrimitive)]
enum Direction {
NORTH = 0,
SOUTH,
EAST,
WEST,
}
fn turn(d: Direction) -> Direction {
FromPrimitive::from_u8((d as u8 + 1) % 4).unwrap()
}
fn main() {
use Direction::*;
for &d in [NORTH, SOUTH, EAST, WEST].iter() {
println!("{:?} -> {:?}", d, turn(d));
}
}
这不需要 unsafe
,因为它使用自动派生的 FromPrimitive
特性.
This does not require unsafe
as it uses the automatically derived FromPrimitive
trait.
这篇关于我如何“切换"通过枚举变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!