Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 18, 2019 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/411d4e920e6683709d17dccca24378ac to your computer and use it in GitHub Desktop.
Save rust-play/411d4e920e6683709d17dccca24378ac to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[derive(Debug)]
struct MyItem1 {
name: String,
}
#[derive(Debug)]
struct MyItem2 {
value: String,
id: u8,
}
#[derive(Debug)]
//Thing1 and Thing2 are required for the serde function. They're the "tags" that identify the generic data
//The above structs are the typed data I'm going to serialize them into
enum StructuredItem {
Thing(MyItem1),
Thing2(MyItem2),
}
trait Printer {
fn do_it(&self) -> ();
}
impl Printer for MyItem1 {
fn do_it(&self) {
println!("{}", self.name)
}
}
impl Printer for MyItem2 {
fn do_it(&self) {
println!("{} with id of {}", self.value, self.id)
}
}
///Is there a way to do this without having to re-implement this here?
impl Printer for StructuredItem {
fn do_it(&self) {
match self {
StructuredItem::Thing(data) => data.do_it(),
StructuredItem::Thing2(data) => data.do_it(),
}
}
}
fn process_item(item: impl Printer) {
item.do_it();
}
fn main() {
let item1: StructuredItem = StructuredItem::Thing(MyItem1 {
name: "nameitem1".to_string(),
});
let item2: StructuredItem = StructuredItem::Thing2(MyItem2 {
value: "valitem1".to_string(),
id: 3,
});
let item3: StructuredItem = StructuredItem::Thing(MyItem1 {
name: "nameitem2".to_string(),
});
//This is where I start. Basically, I've utilized Serde's tagged serialization method
//to specify a Struct from generic data. All structs implement the same trait but now they're
//wrapped in an Option and an Enum
let items = vec![Some(item1), Some(item2), Some(item3)];
std::dbg!(&items);
for item in items {
match item {
Some(StructThing) => process_item(StructThing),
None => println!("Couldn't print the thing {:?}", item),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment