Generic BufReader?

Viewed 244

I want to pass a BufReader instance to a separate function:

use std::fs::File;
use std::io::BufReader;

fn main() {
    let f = File::open("test.txt")?;
    let mut reader = BufReader::new(f);
    read(reader);
}

fn read(reader: &mut BufReader) {
    // todo
}

but get an error about a missing generic argument for BufReader<R>. What generic parameter to use - String, because that's what I want to read? Sorry for my ignorance - I only know generics from Java.

1 Answers

You can make the type generic, constrained to Read (so your method would work for any type buffered reader that implements Read itself):

fn read<R: Read>(reader: &mut BufReader<R>) {
    // todo
}

Playground

From the documentation:

The BufReader struct adds buffering to any reader.

It can be excessively inefficient to work directly with a Read instance. For example, every call to read on TcpStream results in a system call. A BufReader performs large, infrequent reads on the underlying Read and maintains an in-memory buffer of the results.

Also, check on rust generics

Related