Skip to content

Instantly share code, notes, and snippets.

@Roger
Created May 31, 2020 12:43
Show Gist options
  • Save Roger/c03499d4736bae21962ae1fdc43c288d to your computer and use it in GitHub Desktop.
Save Roger/c03499d4736bae21962ae1fdc43c288d to your computer and use it in GitHub Desktop.
mod states {
pub struct Red;
pub struct Yellow;
pub struct Green;
}
fn red(_traffic_light: &TrafficLight<states::Red>) {}
fn yellow(_traffic_light: &TrafficLight<states::Yellow>) {}
fn green(_traffic_light: &TrafficLight<states::Green>) {}
struct TrafficLight<COLOR> {
_color: COLOR,
}
impl TrafficLight<states::Red> {
fn new() -> TrafficLight<states::Red> {
TrafficLight {
_color: states::Red,
}
}
}
impl TrafficLight<states::Red> {
fn next(&self) -> TrafficLight<states::Yellow> {
TrafficLight {
_color: states::Yellow,
}
}
}
impl TrafficLight<states::Yellow> {
fn next(&self) -> TrafficLight<states::Green> {
TrafficLight {
_color: states::Green,
}
}
}
impl TrafficLight<states::Green> {
fn next(&self) -> TrafficLight<states::Red> {
TrafficLight {
_color: states::Red,
}
}
}
fn main() {
let traffic_light = TrafficLight::new();
red(&traffic_light);
// compile error
// yellow(&traffic_light);
let traffic_light = traffic_light.next();
yellow(&traffic_light);
// compile error
// green(&traffic_light);
let traffic_light = traffic_light.next();
green(&traffic_light);
// compile error
// red(&traffic_light);
let traffic_light = traffic_light.next();
red(&traffic_light);
// compile error
// yellow(&traffic_light);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment