Timon Post
Timon Post

Reputation: 2889

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

I am trying to cast Stdout to 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,
        }
    }
}

The compiler is complaining:

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,
   |                     ^^^^^^^^^^^^

I want to cast this and tried to do what the compiler suggested but then it is saying that the as keyword could only be used for primitives and that I should implement the From trait.

How could I cast the Stdout as a Write trait?

Upvotes: 1

Views: 1832

Answers (1)

Shepmaster
Shepmaster

Reputation: 430673

cast Stdout to Write

This does not make sense because Write isn't a type that you cast to. Write is a trait. There are trait objects that are types though, such as Box<Write> or &Write. Re-read the trait objects chapter of The Rust Programming Language to refresh your memory on this topic. Rust 1.27 is going to improve the syntax here to make it more obvious as Box<dyn Write> / &dyn Write.

You could use Box::new(io::stdout()) as Box<Write>, but you'll quickly run into "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>,
        }
    }
}

See also:

Upvotes: 3

Related Questions