xis
xis

Reputation: 24850

How do I treat a String as a File in Rust?

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?

Upvotes: 1

Views: 375

Answers (1)

Mikdore
Mikdore

Reputation: 799

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()
}  

Upvotes: 2

Related Questions