Home > OS >  How do I treat a String as a File in Rust?
How do I treat a String as a File in Rust?

Time:11-07

In Python it is possible to write

from io import StringIO

with StringIO("some text...") as stream:
    for line in stream:
        # work with the data
        process_line(line)

Is there a way I can do the same thing, treat some string as a file object, and apply Read trait to it?

CodePudding user response:

Yes, you can use std::io::Cursor:

use std::io::{Read, Cursor};

fn use_read_trait(s: String, buff: &mut [u8]) -> usize {
    let mut c = Cursor::new(s);
    c.read(buff).unwrap()
}  
  • Related