Skip to content

Instantly share code, notes, and snippets.

@decatur
Created September 11, 2023 12:59
Show Gist options
  • Save decatur/27057c16b78305c11dcd7da79daec236 to your computer and use it in GitHub Desktop.
Save decatur/27057c16b78305c11dcd7da79daec236 to your computer and use it in GitHub Desktop.
Example of a container using enum
/// https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=35d62d49d15756d1116d620099f324ae
/// Example of a container using enum.
use std::collections::HashMap;
use serde::Serialize;
#[derive(Debug, Serialize)]
struct PlantA {
id: String,
}
#[derive(Debug, Serialize)]
struct PlantB {
id: String,
}
impl PlantA {
fn do_some(&self) { println!("{:?}", self); }
}
impl PlantB {
fn do_some(&self) { println!("{:?}", self); }
}
#[derive(Debug, Serialize)]
enum Plant {
A(PlantA),
B(PlantB),
}
impl Plant {
fn do_some(&self) {
match self {
Plant::A(plant) => plant.do_some(),
Plant::B(plant) => plant.do_some(),
};
}
}
type Plants = HashMap<String, Plant>;
enum Job {
NoOp,
ExecPlant(String),
}
impl Job {
fn execute(&self, plants: &Plants) {
match self {
Job::ExecPlant(id) => plants.get(id).unwrap().do_some(),
Job::NoOp => (),
};
}
}
fn main() {
let plants = vec![Plant::A(PlantA {id: "PA".to_owned()}), Plant::B(PlantB {id: "PB".to_owned()})];
let plants: Plants = plants.into_iter().map(|item|
match item {
Plant::A(plant) => (plant.id.clone(), Plant::A(plant)),
Plant::B(plant) => (plant.id.clone(), Plant::B(plant)),
}).collect();
// -> json: {"PA":{"A":{"id":"PA"}},"PB":{"B":{"id":"PB"}}}
println!("json: {}", serde_json::to_string(&plants).expect("Serialize plants"));
for plant in plants.values() {
plant.do_some();
}
plants.get("PA").unwrap().do_some();
let job_queue = vec![Job::ExecPlant("PA".to_owned())];
for job in job_queue {
job.execute(&plants);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment