Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created December 12, 2018 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/d4a2d79b002162d726fef2466c8b1dd2 to your computer and use it in GitHub Desktop.
Save rust-play/d4a2d79b002162d726fef2466c8b1dd2 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait StateSet {
fn next(self) -> (u32, Self);
}
trait State {
type S: StateSet;
fn next(self) -> (u32, Self::S);
}
macro_rules! delegate {
($fn:ident => enum $name:ident { $($variant:tt,)*}) => {
#[derive(Debug)]
enum $name {
$($variant($variant),)+
}
impl StateSet for $name {
fn next(self) -> (u32, Self) {
match self {
$(
$name::$variant(e) => e.$fn(),
)+
}
}
}
}
}
#[derive(Debug)]
struct First(u32);
#[derive(Debug)]
struct Second;
#[derive(Debug)]
struct Third;
impl State for First {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(self.0 + 1, SMTP::Second(Second))
}
}
impl State for Second {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(2, SMTP::Third(Third))
}
}
impl State for Third {
type S = SMTP;
fn next(self) -> (u32, Self::S) {
(3, SMTP::First(First(4)))
}
}
delegate!{next =>
enum SMTP {
First,
Second,
Third,
}
}
fn main() {
let machine = SMTP::First(First(0));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
let (n, machine) = machine.next();
println!("{:?}", (n, &machine));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment