Using an enumeration in a structure results in an "unresolved name" error

I come from C programming and started learning Rust.

Is it possible to use enumin the structure, as in the code fragment below?

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};

When I compile the code, it complains that EastDirectionit is not known.

+4
source share
1 answer

Yes it is possible. In Rust, enumoptions (for example EastDirection) are not in the global namespace by default . To create an instance TrafficLight, write:

let mut t1 = TrafficLight {
    direction: Direction::EastDirection,
    time_elapse: 0,
};

Please note that since variants are not part of the global namespace, you should not repeat the name enumin the variant name. Therefore, it is better to change it to:

enum Direction {
    East,
    West,
}

/* struct TrafficLight */

let mut tl = TrafficLight {
    direction: Direction::East, 
    time_elapse: 0
};
+6

Source: https://habr.com/ru/post/1628752/


All Articles