gpt4 book ai didi

casting - 转换为未调整大小的类型 : `std::io::Stdout` as `std::io::Write` error

转载 作者:行者123 更新时间:2023-11-29 08:26:58 27 4
gpt4 key购买 nike

我正在尝试将 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是一种特质。有 trait objects 是类型,例如 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>,
}
}
}

另见:

关于casting - 转换为未调整大小的类型 : `std::io::Stdout` as `std::io::Write` error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50649557/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com