转换为unsized类型:`std :: io :: Stdout`为`std :: io :: Write`错误

时间:2018-06-01 18:56:07

标签: casting rust traits

我正在尝试将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特质?

1 个答案:

答案 0 :(得分:2)

  

Stdout投放到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>,但很快就会遇到"Expected type parameter" error in the constructor of a generic struct

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

另见: