Skip to content

Commit 7b42bc0

Browse files
committed
Less unwrap() in documentation
1 parent 5f23ef7 commit 7b42bc0

File tree

12 files changed

+76
-50
lines changed

12 files changed

+76
-50
lines changed

library/alloc/src/collections/binary_heap/mod.rs

Lines changed: 1 addition & 2 deletions
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));

library/core/src/cell/once.rs

Lines changed: 7 additions & 5 deletions
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]

library/core/src/fmt/mod.rs

Lines changed: 7 additions & 4 deletions
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 {

library/core/src/iter/sources/once.rs

Lines changed: 2 additions & 1 deletion
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> {

library/core/src/iter/traits/iterator.rs

Lines changed: 3 additions & 3 deletions
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
/// ```

library/core/src/option.rs

Lines changed: 7 additions & 1 deletion
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

library/core/src/ptr/const_ptr.rs

Lines changed: 6 additions & 3 deletions
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"]

library/core/src/result.rs

Lines changed: 8 additions & 3 deletions
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

library/core/src/str/converts.rs

Lines changed: 3 additions & 2 deletions
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:

library/core/src/sync/atomic.rs

Lines changed: 2 additions & 2 deletions
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);

0 commit comments

Comments
 (0)