在结构中使用枚举会导致"未解析的名称"错误

teh*_*yit 4 rust

我来自C编程背景,并开始学习Rust.

是否可以enum在下面的代码片段中使用结构?

enum Direction {
    EastDirection,
    WestDirection
}

struct TrafficLight {
    direction: Direction,  // the direction of the traffic light
    time_elapse : i32,  // the counter used for the elpase time
}

let mut tl = TrafficLight {direction:EastDirection, time_elapse:0};
Run Code Online (Sandbox Code Playgroud)

当我编译代码时,它抱怨EastDirection不知道.

Luk*_*odt 6

是的,这是可能的.在Rust中,enum变体(例如EastDirection)默认情况下不在全局命名空间中.要创建您的TrafficLight实例,请写:

let mut t1 = TrafficLight {
    direction: Direction::EastDirection,
    time_elapse: 0,
};
Run Code Online (Sandbox Code Playgroud)

请注意,由于变体不在全局命名空间中,因此不应enum在变体名称中重复该名称.所以最好把它改成:

enum Direction {
    East,
    West,
}

/* struct TrafficLight */

let mut tl = TrafficLight {
    direction: Direction::East, 
    time_elapse: 0
};
Run Code Online (Sandbox Code Playgroud)