Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic BufReader?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading