【发布时间】:2015-06-04 00:42:52
【问题描述】:
我想为我的代码中常用的嵌套结构实现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> 时,我发现 Display 没有实现。我可以为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!() 需要作为函数的返回值,但会因多次调用而崩溃。
如何漂亮地打印我的结构的 Vec?
【问题讨论】: