Skip to content

Instantly share code, notes, and snippets.

@hyone
Last active April 2, 2022 08:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyone/d6018ee1ac8f9496fed839f481eb59d6 to your computer and use it in GitHub Desktop.
Save hyone/d6018ee1ac8f9496fed839f481eb59d6 to your computer and use it in GitHub Desktop.
Practice: implement `Display` trait for `slice` wrapper
use std::fmt::{ Debug, Display, Formatter, Result };
use std::string::ToString;
#[derive(Debug)]
struct Slice<'a, T: 'a> {
data: &'a [T]
}
impl <'a, T: ToString> Display for Slice<'a, T> {
fn fmt(&self, f: &mut Formatter) -> Result {
let xs: Vec<_> = self.data.into_iter().map(|i| i.to_string()).collect();
write!(f, "[{}]", xs.join(", "))
}
}
fn double_prints<T: Debug + Display>(t: &T) {
println!("Debug: `{:?}`", t);
println!("Display: `{}`", t);
}
fn main() {
let array = ["hello", "world", "rust", "programming"];
let vec: Vec<_> = (1..11).collect();
double_prints(&Slice { data: &array });
//=> Debug: `Slice { data: ["hello", "world", "rust", "programming"] }`
// Display: `[hello, world, rust, programming]`
double_prints(&Slice { data: &vec })
//=> Debug: `Slice { data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }`
// Display: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment