How do I write to an in-memory buffered String?

I'm using the sitemap crate and I'm trying to figure out how to write to a buffered in-memory String in Rust.

let mut buffer = BufWriter::new(io::stdout()); // -- here, how do I put in a String?
let sitemap_writer = SiteMapWriter::new(buffer);

The above example is for stdout and I've seen other examples for output to files. However, I just want to write to an in-memory String. How do I do that?

I'm trying to do something like Java's StringBuffer.

Can anyone please help? Thanks!

io::Write writes bytes which aren't guaranteed to be UTF-8, so you can't write to a String. You can write to a Vec<u8>, though, and turn that into a String.

let buf = BufWriter::new(Vec::new());

// Do writing here.

let bytes = buf.into_inner()?;
let string = String::from_utf8(bytes)?;
1 Like

There's no benefit by wrapping Vec<u8> with BufWriter since writing to in-memory vector doesn't involve any IO/syscall. So this would just be enough.

let mut buf = Vec::new();

io::Cursor is probably the type you're looking for, if it's not just using Vec<u8> or String.

The write! macro works for strings via fmt::Write instead of io::Write.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.