Cannot generically target write/writeln macros

I'm making a generic wrapper around a writer, akin to std::io::BufWriter

So I start with a struct like this:

pub struct MyWriter<W> {
    inner: W

And I add an implementation for std::io::Write types:

use std::io::{Write, Result};

impl<W: Write> Write for MyWriter<W> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        for x in buf {
             writeln!(self.inner, "Byte: {}", byte)?;


    fn flush(&mut self) -> Result<()> {

Notice how my writer will always produce UTF-8 text because it only uses the write! / writeln! macros.

That means I can support Strings, right?


Both impl Write for MyWriter<String> and impl<W: std::fmt::Write> Write for MyWriter<W> give me confliction implementation errors, once because "std might implement io::Write for String" (unlikely, but okay...) and once because W might implement BOTH io::Write AND fmt::Write...

I could instead do impl<W: fmt::Write> fmt::Write for MyWriter<W>, but this means MyWriter<String> would only work with strs, even though any data would be valid.

It would make things like this not possible:

// get some data
let data = std::fs::read("some_file")?;

let mut writer = MyWriter::<String>::new();

// process and write it into a string

// get the inner string and print it (AsRef<W> implementation ommitted for brevity)
println!("{}", writer.as_ref());

What can I do? How can I support String, or any other type using fmt::Write?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.