From ac6ef2bcd31fcc27e45dfa3bcc78cc34cc6648f9 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Wed, 10 Jun 2020 00:59:02 -0400 Subject: [PATCH] Added program to teach how to write display functions for itteratable structures --- testcase.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 testcase.rs diff --git a/testcase.rs b/testcase.rs new file mode 100644 index 0000000..e128799 --- /dev/null +++ b/testcase.rs @@ -0,0 +1,33 @@ +//Import the `fmt` module. +use std::fmt; + +//Define a structure named `List` containing a `Vec`. +struct List(Vec); + +impl fmt::Display for List{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ + //Extract the value using tuple indexing, + //and create a reference to `vec`. + let vec = &self.0; + + write!(f, "[")?; + + //Iterate over `v` in `vec` while enumerating the iteration count in `count`. + for(count, v) in vec.iter().enumerate(){ + //For every element except the first, add a comma. + //Use the ? operator, or try!, to return on errors. + if count != 0{ + write!(f, ", ")?; + } + write!(f, "{}: {}", count, v)?; + } + + //Close the opened bracket and return a fmt::Result value. + write!(f, "]") + } +} + +fn main(){ + let v = List(vec![1, 2, 3]); + println!("{}", v); +}