Read::read_to_string, Cursor
fn read_to_string(&mut self, buf: &mut String) -> Result<usize>
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>Read all remaining bytes into a String, or fail if the bytes are not valid UTF-8. Use read_to_end when the input may be binary.
| Parameter | Description |
|---|---|
buf | The destination String. read_to_string appends; it does not clear the string first. |
Returns: Ok(byte_count) on success. The byte count is the number of bytes appended, which for valid UTF-8 is also the increase in String::len.
Errors and panics
std::io::Error— I/O failures from the reader, or ErrorKind::InvalidData when the bytes are not valid UTF-8. This is a Result, not a panic.
- The success path uses Cursor<Vec<u8>> in memory. The same methods apply to File, but these examples avoid depending on files on disk.
- For the two-byte sequence 0xff 0xfe, read_to_string fails with InvalidData and the destination string stays empty.
- main returns io::Result<()> so that ? can be used. A failure would be reported by the standard Termination implementation.
use std::io::{self, Cursor, Read};
fn main() -> io::Result<()> {
let mut cursor = Cursor::new(Vec::from(*b"hello"));
let mut text = String::new();
let n = cursor.read_to_string(&mut text)?;
println!("n={n} text={text}");
let mut bad = Cursor::new(vec![0xff, 0xfe]);
let mut invalid = String::new();
let err = bad.read_to_string(&mut invalid).unwrap_err();
println!("invalid kind={:?} empty={}", err.kind(), invalid.is_empty());
Ok(())
}Expected output
n=5 text=hello
invalid kind=InvalidData empty=trueRelated: Read::read_to_string, Read::read_to_end