转换为未调整大小的类型:`std::io::Stdout` 作为 `std::io::Write` 错误

Cast to unsized type: `std::io::Stdout` as `std::io::Write` error

我正在尝试将 Stdout 转换为 Write:

use std::io::{self, Write};

pub struct A<Output: Write> {
    output: Output,
}

impl<Output: Write> A<Output> {
    pub fn new() -> A<Output> {
        A {
            output: io::stdout() as Write,
        }
    }
}

编译器报错:

error[E0620]: cast to unsized type: `std::io::Stdout` as `std::io::Write`
  --> src/main.rs:10:21
   |
10 |             output: io::stdout() as Write,
   |                     ^^^^^^^^^^^^^^^^^^^^^
   |
help: consider using a box or reference as appropriate
  --> src/main.rs:10:21
   |
10 |             output: io::stdout() as Write,
   |                     ^^^^^^^^^^^^

我想转换它并尝试按照编译器的建议进行操作,但它说 as 关键字只能用于原语,我应该实现 From 特性。

如何将 Stdout 转换为 Write 特征?

cast Stdout to Write

这没有意义,因为 Write 不是您将 转换为 的类型。 Write 是一个特征。虽然有 特征对象 是类型,例如 Box<Write>&Write。重新阅读 trait objects chapter of The Rust Programming Language 以刷新您对这个主题的记忆。 Rust 1.27 将改进此处的语法,使其更明显,如 Box<dyn Write> / &dyn Write

您可以使用 Box::new(io::stdout()) as Box<Write>,但您很快就会 运行 进入

impl A<Box<Write>> {
    pub fn new() -> Self {
        A {
            output: Box::new(io::stdout()) as Box<Write>,
        }
    }
}

另请参阅:

  • What makes something a "trait object"?
  • Why is `let ref a: Trait = Struct` forbidden