Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In Ch20, BufReader is initialized using mutable borrow of TcpStream unnecessarily #3957

Closed
bin-wang opened this issue Jun 13, 2024 · 1 comment · Fixed by #4024
Closed

In Ch20, BufReader is initialized using mutable borrow of TcpStream unnecessarily #3957

bin-wang opened this issue Jun 13, 2024 · 1 comment · Fixed by #4024
Labels

Comments

@bin-wang
Copy link
Contributor

bin-wang commented Jun 13, 2024

URL to the section(s) of the book with this problem:
https://doc.rust-lang.org/book/ch20-01-single-threaded.html
https://doc.rust-lang.org/book/ch20-02-multithreaded.html

Description of the problem:
In all the code listings in Chapter 20, a BufReader is used to read the HTTP request. The BufReader is initialized using a mutable borrow of TcpStream:

let buf_reader = BufReader::new(&mut stream);

However, it seems the mutable borrow isn't necessary here. The code works just fine when mut is removed. What's the consideration here?

Suggested fix:

Change the initialization to use immutable borrow.

let buf_reader = BufReader::new(&stream);
@chriskrycho
Copy link
Contributor

Ah, good catch. This one is a case where the way this code was written originally did require a mutable reference, because it was originally written like this, using std::io::Read::read, which takes a buffer by mutable reference:

    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();

When it switched over to using BufReader, the &mut stuck around, even though it is not necessary for BufReader::new. I’ll happily merge a PR which drops it (or try to hit it myself at some point).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants