为什么 Vec<T>实现显示特性? [英] Why doesn't Vec<T> implement the Display trait?

查看:21
本文介绍了为什么 Vec<T>实现显示特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习这门语言让我感到惊讶我无法打印 Vec 的实例:

Learning the language it's been surprising to me I cannot print an instance of Vec:

fn main() {
    let v1 = vec![1, 2, 3];
    println!("{}", v1);
}

error[E0277]: `std::vec::Vec<{integer}>` doesn't implement `std::fmt::Display`
 --> src/main.rs:3:20
  |
3 |     println!("{}", v1);
  |                    ^^ `std::vec::Vec<{integer}>` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `std::vec::Vec<{integer}>`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: required by `std::fmt::Display::fmt`

我可以理解,并且我知道使用 {:?} 调试占位符,如此处.不幸的是,我还不明白为什么我不能这样做的答案.对于 C# 或 Haskell 来说,这将是一项非常微不足道的任务,不是吗?对于任何可序列化(或可转换为 String)的 T,我会为 Vec 实现 Display trait>).我可以对为什么我不能这样做有不同的解释吗?是类型系统的限制吗?

I can understand that and I'm aware of using {:?} debug placeholder as described here. Unfortunately, I don't yet understand the answer that tells why I cannot do that. It would be pretty trivial task for either C# or Haskell, wouldn't it? I'd implement the Display trait for Vec<T> for any T that is serializable (or convertible to String). Can I have a different explanation on why I can't do that? Is it a limitation of the type system?

推荐答案

首先,您不能为外部类型实现外部特征,这就是 链接 ker 提供的链接是关于.

First, you can't implement a foreign trait for a foreign type, that's what the question and answer the link to which ker has provided are about.

原则上,没有什么可以阻止在定义了Vec 的模块中为Vec 实现Display(最有可能在collections::vec).然而,这是故意不这样做的.正如 thisthis RFC,Display 特性旨在生成应显示给用户的字符串.但是,没有自然的方法可以从向量生成这样的字符串.你想要逗号分隔的项目还是制表符分隔的项目?它们应该用方括号或花括号括起来还是什么都不用?也许您想在单独的行上打印每个元素?没有一种方法.

In principle, nothing prevents implementing Display for Vec in a module where either of them is defined (most likely in collections::vec). However, this is intentionally not done. As is explained in this and this RFCs, the Display trait is intended to produce strings which should be displayed to the user. However, there is no natural way to produce such a string from a vector. Do you want comma-separated items or tab-separated ones? Should they be wrapped in brackets or curly braces or nothing? Maybe you want to print each element on its separate line? There is no one single way.

解决此问题的最简单方法是使用新类型包装器.例如:

The simplest way to work around this would be to use a newtype wrapper. For example:

use std::fmt;

struct SliceDisplay<'a, T: 'a>(&'a [T]);

impl<'a, T: fmt::Display + 'a> fmt::Display for SliceDisplay<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut first = true;
        for item in self.0 {
            if !first {
                write!(f, ", {}", item)?;
            } else {
                write!(f, "{}", item)?;
            }
            first = false;
        }
        Ok(())
    }
}

fn main() {
    let items = vec![1, 2, 3, 4];
    println!("{}", SliceDisplay(&items));
}

这篇关于为什么 Vec&lt;T&gt;实现显示特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆