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
let buf = BufWriter::new(Vec::new());
// Do writing here.
let bytes = buf.into_inner()?;
let string = String::from_utf8(bytes)?;
There's no benefit by wrapping
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
write! macro works for strings via
fmt::Write instead of
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.