Skip to content

Commit efb65e9

Browse files
committed
add comments
Signed-off-by: tison <[email protected]>
1 parent a4c30c4 commit efb65e9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

library/core/src/cell/once.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,30 @@ impl<T> OnceCell<T> {
164164
}
165165
}
166166

167+
/// Gets the mutable reference of the contents of the cell,
168+
/// initializing it with `f` if the cell was empty.
169+
///
170+
/// # Panics
171+
///
172+
/// If `f` panics, the panic is propagated to the caller, and the cell
173+
/// remains uninitialized.
174+
///
175+
/// It is an error to reentrantly initialize the cell from `f`. Doing
176+
/// so results in a panic.
177+
///
178+
/// # Examples
179+
///
180+
/// ```
181+
/// use std::cell::OnceCell;
182+
///
183+
/// let mut cell = OnceCell::new();
184+
/// let value = cell.get_mut_or_init(|| 92);
185+
/// assert_eq!(value, &92);
186+
/// *value += 2;
187+
/// assert_eq!(value, &94);
188+
/// let value = cell.get_mut_or_init(|| unreachable!());
189+
/// assert_eq!(value, &94);
190+
/// ```
167191
#[inline]
168192
#[stable(feature = "once_cell", since = "1.70.0")]
169193
pub fn get_mut_or_init<F>(&mut self, f: F) -> &mut T
@@ -214,6 +238,35 @@ impl<T> OnceCell<T> {
214238
self.try_init(f)
215239
}
216240

241+
/// Gets the mutable reference of the contents of the cell, initializing
242+
/// it with `f` if the cell was empty. If the cell was empty and `f` failed,
243+
/// an error is returned.
244+
///
245+
/// # Panics
246+
///
247+
/// If `f` panics, the panic is propagated to the caller, and the cell
248+
/// remains uninitialized.
249+
///
250+
/// It is an error to reentrantly initialize the cell from `f`. Doing
251+
/// so results in a panic.
252+
///
253+
/// # Examples
254+
///
255+
/// ```
256+
/// #![feature(once_cell_try)]
257+
///
258+
/// use std::cell::OnceCell;
259+
///
260+
/// let mut cell = OnceCell::new();
261+
/// assert_eq!(cell.get_mut_or_try_init(|| Err(())), Err(()));
262+
/// assert!(cell.get().is_none());
263+
/// let value = cell.get_mut_or_try_init(|| -> Result<i32, ()> {
264+
/// Ok(92)
265+
/// });
266+
/// assert_eq!(value, Ok(&mut 92));
267+
/// *value.unwrap() += 2;
268+
/// assert_eq!(cell.get(), Some(&94))
269+
/// ```
217270
#[unstable(feature = "once_cell_try", issue = "109737")]
218271
pub fn get_mut_or_try_init<F, E>(&mut self, f: F) -> Result<&mut T, E>
219272
where

0 commit comments

Comments
 (0)