简体   繁体   中英

Creating a struct with a generic trait for field. Expected struct<trait> found struct<type that implements said trait>

I'm trying to create a struct that has a BufWriter that uses the Write trait, so that this struct could have a buffered writer that can be anything that implements that trait: File , Stream , etc. But I'm having an issue in my function that creates the struct saying that I have mismatched types . Here is an example code with the same issue.

use std::fs::File;
use std::io::{BufWriter, Write};

pub struct BufWriterStruct<W: Write> {
    pub writer: Option<BufWriter<W>>,
}

impl <W: Write>BufWriterStruct<W> {
    pub fn new(filename: &str) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(File::create(filename).unwrap())),
        }
    }
}

fn main() {
    let tmp = BufWriterStruct::new("tmp.txt");
}

Playground

with the error

error: mismatched types:
 expected `BufWriterStruct<W>`,
    found `BufWriterStruct<std::fs::File>`

If instead I change my new function to instead take a parameter that implements the Write trait and use that when creating BufWriter , it works fine.

I feel like the former should be possible to do somehow.

impl <W: Write>BufWriterStruct<W> {
    pub fn new(filename: &str) -> BufWriterStruct<W>

This signature means that the following code would be valid:

let tmp : BufWriterStruct<Stdout> = BufWriterStruct::new("tmp.txt");

However this would clearly not work with your implementation of new , as it produces a BufWriterStruct<File> , not <StdOut> . If you want to return a BufWriterStruct<File> , you should declare your new function accordingly:

pub fn new(filename: &str) -> BufWriterStruct<File>

However, this change alone will leave the W parameter on the impl block unconstrained, and the compiler will be unable to infer a type for it. The best solution for this would be to put the new method on a non-generic impl :

impl BufWriterStruct<File> {
    pub fn new(filename: &str) -> BufWriterStruct<File> {
        // ...
    }
}

Note that Rust doesn't support overloading (methods with the same name but different parameter lists), so if you had two impl blocks on the same type (disregarding generic parameters) each with a method named new , you'd get an error when trying to invoke one of them (as of Rust 1.4.0, merely defining methods with the same name in separate impl blocks is not a compile-time error). Therefore, you might wish to use a more explicit name than new .

Your error is in mixing generic and specific:

impl <W: Write>BufWriterStruct<W> {
    pub fn new(filename: &str) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(File::create(filename).unwrap())),
        }
    }
}

Here, your instance of BufWriter should accept a W: Write , which is decided by the caller , yet the function actually creates a File .

Let the caller decide, instead:

impl <W: Write> BufWriterStruct<W> {
    pub fn new(writer: W) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(writer)),
        }
    }
}

Of course, this will change invocation a bit:

fn main() {
    let tmp = BufWriterStruct::new(File::create("tmp.txt").unwrap());
}

And then it'll work .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM