如何通过枚举变体“切换”?

时间:2014-09-16 11:43:14

标签: rust

我想编写一个函数,将提供的值切换/切换到枚举中的下一个并在结尾处回绕:

enum Direction { NORTH, SOUTH, EAST, WEST }

例如,NORTH => SOUTHSOUTH => EASTEAST => WESTWEST => NORTH

是否比In Rust, is there a way to iterate through the values of an enum?

中描述的手动创建静态数组更简单
use Direction::*;
static DIRECTIONS: [Direction; 4] = [NORTH, SOUTH, EAST, WEST];

Aren的枚举假设是"枚举"?我依稀记得在Rust之前看过一个例子,但我似乎无法找到它。由于Rust枚举更像是工会/变体,我想这会让事情复杂化。

3 个答案:

答案 0 :(得分:7)

我想这样的事情可以解决问题:

#[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特征。

答案 1 :(得分:6)

弗拉基米尔的答案是正确的,但程序员必须记住在向enum添加新成员时更改幻数“4”。 turn的这个定义应该更容易维护:

#[derive(Debug, Copy, Clone, FromPrimitive)]
enum Direction {
    NORTH = 0,
    SOUTH,
    EAST,
    WEST,
}

fn turn(d: Direction) -> Direction {
    match FromPrimitive::from_u8(d as u8 + 1) {
        Some(d2) => d2,
        None => FromPrimitive::from_u8(0).unwrap(),
    }
}

答案 2 :(得分:4)

我更愿意通过for i in attrs: match=re.search('(\d)GB',i) if match: if match.group(2)<8: print names 语句显式编码下一个方向:

match