Skip to content

Commit 931151f

Browse files
authored
Rollup merge of rust-lang#59532 - mbrubeck:docs, r=Centril
In doc examples, don't ignore read/write results Calling `Read::read` or `Write::write` without checking the returned `usize` value is almost always an error. Example code in the documentation should demonstrate how to use the return value correctly. Otherwise, people might copy the example code thinking that it is okay to "fire and forget" these methods.
2 parents 183afcd + b6fb3e3 commit 931151f

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/libstd/io/mod.rs

+19-6
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@
2424
//! let mut buffer = [0; 10];
2525
//!
2626
//! // read up to 10 bytes
27-
//! f.read(&mut buffer)?;
27+
//! let n = f.read(&mut buffer)?;
2828
//!
29-
//! println!("The bytes: {:?}", buffer);
29+
//! println!("The bytes: {:?}", &buffer[..n]);
3030
//! Ok(())
3131
//! }
3232
//! ```
@@ -56,9 +56,9 @@
5656
//! f.seek(SeekFrom::End(-10))?;
5757
//!
5858
//! // read up to 10 bytes
59-
//! f.read(&mut buffer)?;
59+
//! let n = f.read(&mut buffer)?;
6060
//!
61-
//! println!("The bytes: {:?}", buffer);
61+
//! println!("The bytes: {:?}", &buffer[..n]);
6262
//! Ok(())
6363
//! }
6464
//! ```
@@ -537,7 +537,9 @@ pub trait Read {
537537
/// let mut buffer = [0; 10];
538538
///
539539
/// // read up to 10 bytes
540-
/// f.read(&mut buffer[..])?;
540+
/// let n = f.read(&mut buffer[..])?;
541+
///
542+
/// println!("The bytes: {:?}", &buffer[..n]);
541543
/// Ok(())
542544
/// }
543545
/// ```
@@ -1062,12 +1064,23 @@ impl Initializer {
10621064
/// use std::fs::File;
10631065
///
10641066
/// fn main() -> std::io::Result<()> {
1067+
/// let data = b"some bytes";
1068+
///
1069+
/// let mut pos = 0;
10651070
/// let mut buffer = File::create("foo.txt")?;
10661071
///
1067-
/// buffer.write(b"some bytes")?;
1072+
/// while pos < data.len() {
1073+
/// let bytes_written = buffer.write(&data[pos..])?;
1074+
/// pos += bytes_written;
1075+
/// }
10681076
/// Ok(())
10691077
/// }
10701078
/// ```
1079+
///
1080+
/// The trait also provides convenience methods like [`write_all`], which calls
1081+
/// `write` in a loop until its entire input has been written.
1082+
///
1083+
/// [`write_all`]: #method.write_all
10711084
#[stable(feature = "rust1", since = "1.0.0")]
10721085
#[doc(spotlight)]
10731086
pub trait Write {

0 commit comments

Comments
 (0)