Creating a struct with a generic trait for field. Expected struct found struct

后端 未结 2 611
北恋
北恋 2020-12-22 02:16

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 anythin

相关标签:
2条回答
  • 2020-12-22 02:45

    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.

    0 讨论(0)
  • 2020-12-22 03:00
    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.

    0 讨论(0)
提交回复
热议问题