我正在尝试将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
特质?
答案 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>,
}
}
}
另见: