Skip to content

Instantly share code, notes, and snippets.

@ueokande
Created June 13, 2019 04:01
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 ueokande/2e66c428876cd9ffa4845c137b584416 to your computer and use it in GitHub Desktop.
Save ueokande/2e66c428876cd9ffa4845c137b584416 to your computer and use it in GitHub Desktop.
x
struct Document<'a> {
fields: Vec<Box<Field + 'a>>,
}
impl<'a> Document<'a> {
fn new() -> Document<'a> {
Document { fields: Vec::new() }
}
fn add_field<T>(&mut self, field: T)
where
T: Field + 'a,
{
self.fields.push(Box::new(field))
}
}
struct TextField {
name: String,
value: String,
}
trait Field {
fn name(&self) -> &str;
fn string_value(&self) -> &str;
}
impl TextField {
fn new(name: &str, value: &str) -> TextField {
TextField {
name: name.into(),
value: value.into(),
}
}
}
impl Field for TextField {
fn name(&self) -> &str {
&self.name
}
fn string_value(&self) -> &str {
&self.value
}
}
fn main() {
let mut doc = Document::new();
doc.add_field(TextField::new("title", "Rust in Action"));
doc.add_field(TextField::new("isbn", "12345678"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment