Implement fmt::Display for Vec

As this error states, you cannot implement a trait for a type you don’t own:

the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types

However, you can implement Display for your wrapper type. The piece you are missing is to use the try! macro or the try operator ?:

use std::fmt;

struct Foo(Vec<u8>);

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Values:\n")?;
        for v in &self.0 {
            write!(f, "\t{}", v)?;
        }
        Ok(())
    }
}

fn main() {
    let f = Foo(vec![42]);
    println!("{}", f);
}

Leave a Comment