本文介绍了如何打印 Vec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码:

fn main() {
    let v2 = vec![1; 10];
    println!("{}", v2);
}

但是编译器抱怨:

error[E0277]: `std::vec::Vec<{integer}>` doesn't implement `std::fmt::Display`
 --> src/main.rs:3:20
  |
3 |     println!("{}", v2);
  |                    ^^ `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`

有没有人为 Vec 实现这个特性?

Does anyone implement this trait for Vec<T>?

推荐答案

没有

令人惊讶的是,这是一个明显正确的答案;这很少见,因为证明事物不存在通常很难或不可能.那么我们怎么能这么确定呢?

And surprisingly, this is a demonstrably correct answer; which is rare since proving the absence of things is usually hard or impossible. So how can we be so certain?

Rust 有非常严格的一致性规则,impl Trait for Struct 只能做到:

Rust has very strict coherence rules, the impl Trait for Struct can only be done:

  • Trait
  • 位于同一个板条箱中
  • 或与 Struct
  • 放在同一个板条箱中
  • either in the same crate as Trait
  • or in the same crate as Struct

没有其他地方;让我们试试:

and nowhere else; let's try it:

impl<T> std::fmt::Display for Vec<T> {
    fn fmt(&self, _: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        Ok(())
    }
}

产量:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> src/main.rs:1:1
  |
1 | impl<T> std::fmt::Display for Vec<T> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: only traits defined in the current crate can be implemented for a type parameter

此外,要使用特征,它需要在范围内(因此,您需要链接到它的箱子),这意味着:

Furthermore, to use a trait, it needs to be in scope (and therefore, you need to be linked to its crate), which means that:

  • 你同时与 Display 的 crate 和 Vec 的 crate 相关联
  • 都不为Vec
  • 实现Display
  • you are linked both with the crate of Display and the crate of Vec
  • neither implement Display for Vec

因此导致我们得出结论,没有人为 Vec 实现 Display.

and therefore leads us to conclude that no one implements Display for Vec.

作为一种变通方法,如 Manishearth 所指出的,您可以使用 Debug 特性,该特性可通过 "{:?}" 作为格式说明符调用.

As a work around, as indicated by Manishearth, you can use the Debug trait, which is invokable via "{:?}" as a format specifier.

这篇关于如何打印 Vec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 15:14