printf - 为 Vec<T> 实现 fmt::Display

标签 printf rust traits

我想实现 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/

相关文章:

arrays - 如何使用泛型和特征从数组中获取最大的元素?

ios - 如何将 printf 输出定向到与 NSLog 相同的目标?

java - 如何使我的 println 以我想要的方式在这个 for 循环中打印多行打印轮廓/制表符?

csv - 如何在不复制的情况下在 Rust 中迭代 Vec 时分配切片?

rust - 构造具有特征约束的任何类型的向量

generics - 如何实现涉及特征对象内置类型的通用可交换 std::ops?

c - if 字符串比较语句未正确执行

c - 将十六进制字节转换为字符字符串

rust - 如何为自定义 IntoIterator::Item 实现 std::fmt::Display?

multithreading - 如何为 RustBox 实现 Sync?