-
-
Save ueokande/2e66c428876cd9ffa4845c137b584416 to your computer and use it in GitHub Desktop.
x
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
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