我想实现 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
}
如您所见,这是一个非常重要的数据树。 archive_infos
属性(property) Header
当显示为一行时可能会很长。
我想发出一些类似的东西
WhisperFile ({PATH})
Metadata
...
ArchiveInfo (0)
...
ArchiveInfo (N)
...
但是当我尝试显示 Vec<ArchiveInfo>
时我知道 Display 没有实现。我可以实现 fmt::Display
对于 ArchiveInfo
但这还不够 fmt::Display
未为父容器实现 Vec
.如果我为 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?
最佳答案
如该错误所述,您不能为您不拥有的类型实现特征:
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);
}
关于printf - 为 Vec<T> 实现 fmt::Display,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633177/