Skip to content

Commit 9f440a5

Browse files
kornelskigitbot
authored and
gitbot
committed
Less unwrap() in documentation
1 parent d38b5d4 commit 9f440a5

File tree

12 files changed

+76
-50
lines changed

12 files changed

+76
-50
lines changed

alloc/src/collections/binary_heap/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -531,8 +531,7 @@ impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
531531
/// heap.push(1);
532532
/// heap.push(5);
533533
/// heap.push(2);
534-
/// {
535-
/// let mut val = heap.peek_mut().unwrap();
534+
/// if let Some(mut val) = heap.peek_mut() {
536535
/// *val = 0;
537536
/// }
538537
/// assert_eq!(heap.peek(), Some(&2));

core/src/cell/once.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,9 @@ impl<T> OnceCell<T> {
262262
///
263263
/// let value = cell.get_mut_or_try_init(|| "1234".parse());
264264
/// assert_eq!(value, Ok(&mut 1234));
265-
/// *value.unwrap() += 2;
265+
///
266+
/// let Ok(value) = value else { return; };
267+
/// *value += 2;
266268
/// assert_eq!(cell.get(), Some(&1236))
267269
/// ```
268270
#[unstable(feature = "once_cell_get_mut", issue = "121641")]
@@ -304,8 +306,8 @@ impl<T> OnceCell<T> {
304306
/// assert_eq!(cell.into_inner(), None);
305307
///
306308
/// let cell = OnceCell::new();
307-
/// cell.set("hello".to_string()).unwrap();
308-
/// assert_eq!(cell.into_inner(), Some("hello".to_string()));
309+
/// let _ = cell.set("hello".to_owned());
310+
/// assert_eq!(cell.into_inner(), Some("hello".to_owned()));
309311
/// ```
310312
#[inline]
311313
#[stable(feature = "once_cell", since = "1.70.0")]
@@ -332,8 +334,8 @@ impl<T> OnceCell<T> {
332334
/// assert_eq!(cell.take(), None);
333335
///
334336
/// let mut cell = OnceCell::new();
335-
/// cell.set("hello".to_string()).unwrap();
336-
/// assert_eq!(cell.take(), Some("hello".to_string()));
337+
/// let _ = cell.set("hello".to_owned());
338+
/// assert_eq!(cell.take(), Some("hello".to_owned()));
337339
/// assert_eq!(cell.get(), None);
338340
/// ```
339341
#[inline]

core/src/fmt/mod.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,9 @@ pub trait Write {
152152
/// }
153153
///
154154
/// let mut buf = String::new();
155-
/// writer(&mut buf, "hola").unwrap();
155+
/// writer(&mut buf, "hola")?;
156156
/// assert_eq!(&buf, "hola");
157+
/// # std::fmt::Result::Ok(())
157158
/// ```
158159
#[stable(feature = "rust1", since = "1.0.0")]
159160
fn write_str(&mut self, s: &str) -> Result;
@@ -179,9 +180,10 @@ pub trait Write {
179180
/// }
180181
///
181182
/// let mut buf = String::new();
182-
/// writer(&mut buf, 'a').unwrap();
183-
/// writer(&mut buf, 'b').unwrap();
183+
/// writer(&mut buf, 'a')?;
184+
/// writer(&mut buf, 'b')?;
184185
/// assert_eq!(&buf, "ab");
186+
/// # std::fmt::Result::Ok(())
185187
/// ```
186188
#[stable(feature = "fmt_write_char", since = "1.1.0")]
187189
fn write_char(&mut self, c: char) -> Result {
@@ -208,8 +210,9 @@ pub trait Write {
208210
/// }
209211
///
210212
/// let mut buf = String::new();
211-
/// writer(&mut buf, "world").unwrap();
213+
/// writer(&mut buf, "world")?;
212214
/// assert_eq!(&buf, "world");
215+
/// # std::fmt::Result::Ok(())
213216
/// ```
214217
#[stable(feature = "rust1", since = "1.0.0")]
215218
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {

core/src/iter/sources/once.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use crate::iter::{FusedIterator, TrustedLen};
3434
/// use std::fs;
3535
/// use std::path::PathBuf;
3636
///
37-
/// let dirs = fs::read_dir(".foo").unwrap();
37+
/// let dirs = fs::read_dir(".foo")?;
3838
///
3939
/// // we need to convert from an iterator of DirEntry-s to an iterator of
4040
/// // PathBufs, so we use map
@@ -50,6 +50,7 @@ use crate::iter::{FusedIterator, TrustedLen};
5050
/// for f in files {
5151
/// println!("{f:?}");
5252
/// }
53+
/// # std::io::Result::Ok(())
5354
/// ```
5455
#[stable(feature = "iter_once", since = "1.2.0")]
5556
pub fn once<T>(value: T) -> Once<T> {

core/src/iter/traits/iterator.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2564,7 +2564,7 @@ pub trait Iterator {
25642564
/// # Example
25652565
///
25662566
/// ```
2567-
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap();
2567+
/// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
25682568
/// assert_eq!(reduced, 45);
25692569
///
25702570
/// // Which is equivalent to doing it with `fold`:
@@ -3087,7 +3087,7 @@ pub trait Iterator {
30873087
/// [2.4, f32::NAN, 1.3]
30883088
/// .into_iter()
30893089
/// .reduce(f32::max)
3090-
/// .unwrap(),
3090+
/// .unwrap_or(0.),
30913091
/// 2.4
30923092
/// );
30933093
/// ```
@@ -3123,7 +3123,7 @@ pub trait Iterator {
31233123
/// [2.4, f32::NAN, 1.3]
31243124
/// .into_iter()
31253125
/// .reduce(f32::min)
3126-
/// .unwrap(),
3126+
/// .unwrap_or(0.),
31273127
/// 1.3
31283128
/// );
31293129
/// ```

core/src/option.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -937,10 +937,16 @@ impl<T> Option<T> {
937937
/// Returns the contained [`Some`] value, consuming the `self` value.
938938
///
939939
/// Because this function may panic, its use is generally discouraged.
940+
/// Panics are meant for unrecoverable errors, and
941+
/// [may abort the entire program][panic-abort].
942+
///
940943
/// Instead, prefer to use pattern matching and handle the [`None`]
941944
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
942-
/// [`unwrap_or_default`].
945+
/// [`unwrap_or_default`]. In functions returning `Option`, you can use
946+
/// [the `?` (try) operator][try-option].
943947
///
948+
/// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
949+
/// [try-option]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#where-the--operator-can-be-used
944950
/// [`unwrap_or`]: Option::unwrap_or
945951
/// [`unwrap_or_else`]: Option::unwrap_or_else
946952
/// [`unwrap_or_default`]: Option::unwrap_or_default

core/src/ptr/const_ptr.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -502,11 +502,12 @@ impl<T: ?Sized> *const T {
502502
/// let mut out = String::new();
503503
/// while ptr != end_rounded_up {
504504
/// unsafe {
505-
/// write!(&mut out, "{}, ", *ptr).unwrap();
505+
/// write!(&mut out, "{}, ", *ptr)?;
506506
/// }
507507
/// ptr = ptr.wrapping_offset(step);
508508
/// }
509509
/// assert_eq!(out.as_str(), "1, 3, 5, ");
510+
/// # std::fmt::Result::Ok(())
510511
/// ```
511512
#[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
512513
#[must_use = "returns a new pointer rather than modifying its argument"]
@@ -1125,11 +1126,12 @@ impl<T: ?Sized> *const T {
11251126
/// let mut out = String::new();
11261127
/// while ptr != end_rounded_up {
11271128
/// unsafe {
1128-
/// write!(&mut out, "{}, ", *ptr).unwrap();
1129+
/// write!(&mut out, "{}, ", *ptr)?;
11291130
/// }
11301131
/// ptr = ptr.wrapping_add(step);
11311132
/// }
11321133
/// assert_eq!(out, "1, 3, 5, ");
1134+
/// # std::fmt::Result::Ok(())
11331135
/// ```
11341136
#[stable(feature = "pointer_methods", since = "1.26.0")]
11351137
#[must_use = "returns a new pointer rather than modifying its argument"]
@@ -1203,11 +1205,12 @@ impl<T: ?Sized> *const T {
12031205
/// let mut out = String::new();
12041206
/// while ptr != start_rounded_down {
12051207
/// unsafe {
1206-
/// write!(&mut out, "{}, ", *ptr).unwrap();
1208+
/// write!(&mut out, "{}, ", *ptr)?;
12071209
/// }
12081210
/// ptr = ptr.wrapping_sub(step);
12091211
/// }
12101212
/// assert_eq!(out, "5, 3, 1, ");
1213+
/// # std::fmt::Result::Ok(())
12111214
/// ```
12121215
#[stable(feature = "pointer_methods", since = "1.26.0")]
12131216
#[must_use = "returns a new pointer rather than modifying its argument"]

core/src/result.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -1065,10 +1065,15 @@ impl<T, E> Result<T, E> {
10651065
/// Returns the contained [`Ok`] value, consuming the `self` value.
10661066
///
10671067
/// Because this function may panic, its use is generally discouraged.
1068-
/// Instead, prefer to use pattern matching and handle the [`Err`]
1069-
/// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
1070-
/// [`unwrap_or_default`].
1068+
/// Panics are meant for unrecoverable errors, and
1069+
/// [may abort the entire program][panic-abort].
1070+
///
1071+
/// Instead, prefer to use [the `?` (try) operator][try-operator], or pattern matching
1072+
/// to handle the [`Err`] case explicitly, or call [`unwrap_or`],
1073+
/// [`unwrap_or_else`], or [`unwrap_or_default`].
10711074
///
1075+
/// [panic-abort]: https://doc.rust-lang.org/book/ch09-01-unrecoverable-errors-with-panic.html
1076+
/// [try-operator]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
10721077
/// [`unwrap_or`]: Result::unwrap_or
10731078
/// [`unwrap_or_else`]: Result::unwrap_or_else
10741079
/// [`unwrap_or_default`]: Result::unwrap_or_default

core/src/str/converts.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,11 @@ use crate::{mem, ptr};
4747
/// // some bytes, in a vector
4848
/// let sparkle_heart = vec![240, 159, 146, 150];
4949
///
50-
/// // We know these bytes are valid, so just use `unwrap()`.
51-
/// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
50+
/// // We can use the ? (try) operator to check if the bytes are valid
51+
/// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
5252
///
5353
/// assert_eq!("💖", sparkle_heart);
54+
/// # Ok::<_, str::Utf8Error>(())
5455
/// ```
5556
///
5657
/// Incorrect bytes:

core/src/sync/atomic.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
//! // This is fine: `join` synchronizes the code in a way such that the atomic
8787
//! // store happens-before the non-atomic write.
8888
//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
89-
//! handle.join().unwrap(); // synchronize
89+
//! handle.join().expect("thread won't panic"); // synchronize
9090
//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
9191
//! });
9292
//!
@@ -103,7 +103,7 @@
103103
//! // This is fine: `join` synchronizes the code in a way such that
104104
//! // the 1-byte store happens-before the 2-byte store.
105105
//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed));
106-
//! handle.join().unwrap();
106+
//! handle.join().expect("thread won't panic");
107107
//! s.spawn(|| unsafe {
108108
//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
109109
//! differently_sized.store(2, Ordering::Relaxed);

std/src/io/mod.rs

+15-10
Original file line numberDiff line numberDiff line change
@@ -1083,7 +1083,7 @@ pub trait Read {
10831083
/// let f = BufReader::new(File::open("foo.txt")?);
10841084
///
10851085
/// for byte in f.bytes() {
1086-
/// println!("{}", byte.unwrap());
1086+
/// println!("{}", byte?);
10871087
/// }
10881088
/// Ok(())
10891089
/// }
@@ -1995,15 +1995,16 @@ pub trait Seek {
19951995
/// .write(true)
19961996
/// .read(true)
19971997
/// .create(true)
1998-
/// .open("foo.txt").unwrap();
1998+
/// .open("foo.txt")?;
19991999
///
20002000
/// let hello = "Hello!\n";
2001-
/// write!(f, "{hello}").unwrap();
2002-
/// f.rewind().unwrap();
2001+
/// write!(f, "{hello}")?;
2002+
/// f.rewind()?;
20032003
///
20042004
/// let mut buf = String::new();
2005-
/// f.read_to_string(&mut buf).unwrap();
2005+
/// f.read_to_string(&mut buf)?;
20062006
/// assert_eq!(&buf, hello);
2007+
/// # std::io::Result::Ok(())
20072008
/// ```
20082009
#[stable(feature = "seek_rewind", since = "1.55.0")]
20092010
fn rewind(&mut self) -> Result<()> {
@@ -2212,8 +2213,9 @@ fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
22122213
///
22132214
/// let stdin = io::stdin();
22142215
/// for line in stdin.lock().lines() {
2215-
/// println!("{}", line.unwrap());
2216+
/// println!("{}", line?);
22162217
/// }
2218+
/// # std::io::Result::Ok(())
22172219
/// ```
22182220
///
22192221
/// If you have something that implements [`Read`], you can use the [`BufReader`
@@ -2236,7 +2238,8 @@ fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
22362238
/// let f = BufReader::new(f);
22372239
///
22382240
/// for line in f.lines() {
2239-
/// println!("{}", line.unwrap());
2241+
/// let line = line?;
2242+
/// println!("{line}");
22402243
/// }
22412244
///
22422245
/// Ok(())
@@ -2274,14 +2277,15 @@ pub trait BufRead: Read {
22742277
/// let stdin = io::stdin();
22752278
/// let mut stdin = stdin.lock();
22762279
///
2277-
/// let buffer = stdin.fill_buf().unwrap();
2280+
/// let buffer = stdin.fill_buf()?;
22782281
///
22792282
/// // work with buffer
22802283
/// println!("{buffer:?}");
22812284
///
22822285
/// // ensure the bytes we worked with aren't returned again later
22832286
/// let length = buffer.len();
22842287
/// stdin.consume(length);
2288+
/// # std::io::Result::Ok(())
22852289
/// ```
22862290
#[stable(feature = "rust1", since = "1.0.0")]
22872291
fn fill_buf(&mut self) -> Result<&[u8]>;
@@ -2327,12 +2331,13 @@ pub trait BufRead: Read {
23272331
/// let stdin = io::stdin();
23282332
/// let mut stdin = stdin.lock();
23292333
///
2330-
/// while stdin.has_data_left().unwrap() {
2334+
/// while stdin.has_data_left()? {
23312335
/// let mut line = String::new();
2332-
/// stdin.read_line(&mut line).unwrap();
2336+
/// stdin.read_line(&mut line)?;
23332337
/// // work with line
23342338
/// println!("{line:?}");
23352339
/// }
2340+
/// # std::io::Result::Ok(())
23362341
/// ```
23372342
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
23382343
fn has_data_left(&mut self) -> Result<bool> {

0 commit comments

Comments
 (0)