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

后端 未结 2 620
北恋
北恋 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 BufWriterStruct {
        pub fn new(filename: &str) -> BufWriterStruct {
            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  BufWriterStruct {
        pub fn new(writer: W) -> BufWriterStruct {
            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.

提交回复
热议问题