Created
October 23, 2017 15:04
-
-
Save niklasad1/af75268405c5ce150988b17a1654fae0 to your computer and use it in GitHub Desktop.
ooooo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Imagine I have an immutable struct here that must have the same type | |
// but I want to have "compile-time" verified transitions between the states | |
// with a "state enum" that hold different types | |
#[derive(Debug)] | |
struct Foo { | |
state: Option<MyState>, | |
} | |
impl Foo { | |
fn new() -> Foo { | |
Foo { state: Some(MyState::X(Off)) } | |
} | |
} | |
#[derive(Debug)] | |
struct Off; | |
#[derive(Debug)] | |
struct On; | |
#[derive(Debug)] | |
enum MyState { | |
X(Off), | |
Y(On), | |
} | |
trait AsOff { | |
fn turn_on(self) -> On; | |
} | |
impl AsOff for Off { | |
fn turn_on(self) -> On { | |
On{} | |
} | |
} | |
fn main() { | |
let a = Foo::new(); | |
println!("{:?}", a); | |
// quite painful because I can't access the struct inside the enum | |
let aa = match a.state { | |
Some(MyState::X(Off)) => Some(Off), | |
Some(_) => None, | |
None => None, | |
}; | |
let b = match aa { | |
Some(v) => Some(v.turn_on()), | |
None => None, | |
}; | |
println!("{:?}", b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment