Casting 转换为非大小型:`std::io::Stdout`as`std::io::Write`错误
我正试图将Casting 转换为非大小型:`std::io::Stdout`as`std::io::Write`错误,casting,rust,traits,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,
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,
}
}
}
我想转换这个,并尝试按照编译器的建议去做,但是它说as
关键字只能用于原语,我应该实现From
特性
我如何将Stdout
转换为Write
特性
将Stdout
转换为Write
这没有意义,因为Write
不是您强制转换的类型<代码>写入是一种特性。不过,也有属于类型的trait对象,例如Box
或&Write
。请重新阅读以刷新有关此主题的记忆。Rust 1.27将改进这里的语法,使其在Box
/&dyn Write
中更加明显
您可以使用Box::new(io::stdout())作为Box
,但很快就会遇到
impl A{
pub fn new()->Self{
A{
输出:Box::new(io::stdout())作为Box,
}
}
}
另见:
impl A<Box<Write>> {
pub fn new() -> Self {
A {
output: Box::new(io::stdout()) as Box<Write>,
}
}
}