Implement fmt :: Display for Vec <T>
I want to implement fmt::Display
for a nested struct commonly used in my code.
// The root structure
pub struct WhisperFile<'a> {
pub path: &'a str,
pub handle: RefCell<File>,
pub header: Header
}
pub struct Header{
pub metadata: metadata::Metadata,
pub archive_infos: Vec<archive_info::ArchiveInfo>
}
pub struct Metadata {
// SNIP
}
pub struct ArchiveInfo {
// SNIP
}
As you can see, this is a non-trivial data tree. A property archive_infos
on Header
can be quite long if it is presented as a single line.
I would like to emit something along the lines
WhisperFile ({PATH})
Metadata
...
ArchiveInfo (0)
...
ArchiveInfo (N)
...
But when I try to display Vec<ArchiveInfo>
, I get that Display is not implemented. I can implement fmt::Display
for ArchiveInfo
, but this is not enough since it is fmt::Display
not implemented for the parent container Vec
. If I implement fmt :: Display for collections::vec::Vec<ArchiveInfo>
, I get the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types
.
I've tried iterating over vec and calling write!()
, but I couldn't figure out what the control flow should look like. I think it write!()
should be the return value of the function, but this is interrupted by multiple calls.
How can I print the Vec of my structures?
source to share
As this error says, you cannot implement a trait for a type that you do not own:
impl does not refer to any types defined in this box; only traits defined in the current box can be implemented for arbitrary types
However, you can implement Display
for your wrapper type. The piece you're missing is using a macro try!
:
use std::fmt;
struct Foo(Vec<u8>);
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "Values:\n"));
for v in &self.0 { try!(write!(f, "\t{}", v)); }
Ok(())
}
}
fn main() {
let f = Foo(vec![42]);
println!("{}", f);
}
source to share