为 Vec<T> 实现 fmt::Display

Implement fmt::Display for Vec<T>

我想为我的代码中常用的嵌套结构实现 fmt::Display

// 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
}

如您所见,这是一个非常重要的数据树。 Header 上的 archive_infos 属性 显示为一行时可能会很长。

我想发出一些类似

的东西
WhisperFile ({PATH})
  Metadata
    ...
  ArchiveInfo (0)
    ...
  ArchiveInfo (N)
    ...

但是当我尝试显示时 Vec<ArchiveInfo> 我发现显示没有实现。我可以为 ArchiveInfo 实现 fmt::Display,但这还不够,因为没有为父容器 Vec 实现 fmt::Display。如果我为 collections::vec::Vec<ArchiveInfo> 实施 fmt::Display 我得到 the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types.

我已经尝试遍历 vec 并调用 write!() 但我无法弄清楚控制流应该是什么样子。我认为 write!() 需要是函数的 return 值,但会因多次调用而崩溃。

如何漂亮地打印我的结构的 Vec?

如该错误所述,您不能为您不拥有的类型实现特征:

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

但是,您可以为您的包装器类型实施 Display。您缺少的部分是使用 try! 宏或 try 运算符 ?:

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);
}