In the Rust's book final project the code compile and run as expected with cargo run
.
However, clippy
highlights these commented lines with clippy::unused_io_amount
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap(); // clippy: read amount is not handled
// --snip--
stream.write(response.as_bytes()).unwrap(); // clippy: written amount is not handled
stream.flush().unwrap();
The suggest fix is to change read
to read_exact
and write
to write_all
. However, when running with this changes I get the following error:
thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: UnexpectedEof, message: "failed to fill whole buffer" }', src/main.rs:24:36
How to fix the clippy:: unused_io_amount warning to be able to properly run the rust final project code without any warnings and have it to work as expected?
P.s. in the final project listing write_all
is included but the warning for read
continues on.
The stream.write(...).unwrap()
will return the number of bytes that have been written into the stream
. Your warning says that this number is not handled. It means that you should write let bytes_amount = stream.write(...).unwrap();
and then compare bytes_amount
with buffer.len()
.
Why? Because in real life can be a situation when not all data from the buffer were written into the stream. You should handle such situations
The same with the read
function.
Why read_exact
fails. The read_exact
function tries to read bytes to fill a WHOLE buffer but can be a situation the stream ends before the buffer gets filled.