File io BufRead - Why mut?


I have the following code and I simply read a file into a buffer. I use
std::io::BufferRead for the same. BufferRead implements BufRead and Read trait.
One of the methods in the trait definition is read and it is declared as

fn read(&mut self, buf: &mut [u8]) -> Result

The method is invoked through BufReader instance. ( I think instance is better
word than object in Rust .. is it not ? )

My question is why it has to mut ? as its going to be a read only instance.


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

fn main()

    let fd1 = File::open("testfile").expect("File opening error");

    let mut reader = BufReader::new(& fd1); // Why this has to be mut ? 
                                                                    //Why read takes mutable reference 

    let mut buffer : Vec<u8> = vec![0;1000000];

    //let seek_pointer : u64 =0 ;

    //seek_pointer ="Seek Error");

    let n = buffer).expect("Error in reading");

1 Like

BufReader reads data in its internal buffer before writing it into your buffer, so it must have an exclusive reference to itself. Otherwise, it would have to use something like Mutex and lock it on every read - this would ruin the performance.

It might need to mutate itself to either remember how much data you have read, or to retrieve that next chunk of data.



This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.