diff options
author | Adam Carpenter <53hornet@gmail.com> | 2019-03-27 15:32:37 -0400 |
---|---|---|
committer | Adam Carpenter <53hornet@gmail.com> | 2019-03-27 15:32:37 -0400 |
commit | 67cdcc2e12118becb823e20a40cc2687f2b8425a (patch) | |
tree | ed92c3234b89079e6d4cf36f5e80c5ffa79def48 /meap/meap-code/ch3/ch3-implementing-display.rs | |
parent | e25482fca375d318a39c3b54db396b0db6e0b263 (diff) | |
download | learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip |
Started Rust in Action MEAP.
Diffstat (limited to 'meap/meap-code/ch3/ch3-implementing-display.rs')
-rw-r--r-- | meap/meap-code/ch3/ch3-implementing-display.rs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/meap/meap-code/ch3/ch3-implementing-display.rs b/meap/meap-code/ch3/ch3-implementing-display.rs new file mode 100644 index 0000000..8537bd9 --- /dev/null +++ b/meap/meap-code/ch3/ch3-implementing-display.rs @@ -0,0 +1,49 @@ +#![allow(dead_code)] // <1> Silence warnings related to FileState::Open not being used
+
+use std::fmt; // <2> Bring the `std::fmt` crate into local scope, allowing us to make use of `fmt::Result`
+use std::fmt::{Display}; // <3> Bring `Display` into local scope, avoiding the need for us to prefix it as `fmt::Display` in our code
+
+#[derive(Debug,PartialEq)]
+enum FileState {
+ Open,
+ Closed,
+}
+
+#[derive(Debug)]
+struct File {
+ name: String,
+ data: Vec<u8>,
+ state: FileState,
+}
+
+impl Display for FileState {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ FileState::Open => write!(f, "OPEN"), // <4> Sneakily, we can make use of `write!` to do the grunt work for us. Strings already implement `Display` themselves, so there's very little left for us to do.
+ FileState::Closed => write!(f, "CLOSED"), // <4>
+ }
+ }
+}
+
+impl Display for File {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "<{} ({})>", self.name, self.state) // <5> We can rely on the FileState Display implementation in our own code
+ }
+}
+
+impl File {
+ fn new(name: &str) -> File {
+ File {
+ name: String::from(name),
+ data: Vec::new(),
+ state: FileState::Closed
+ }
+ }
+}
+
+fn main() {
+ let f5 = File::new("f5.txt");
+ //...
+ println!("{:?}", f5); // <1>
+ println!("{}", f5); // <1>
+}
\ No newline at end of file |