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
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.
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
.