Skip to content

Commit 8e02ad0

Browse files
committed
Provide Entry-like API for Option
This implements #39288. Thanks to @steveklabnik and @oli-obk for their review comments :)
1 parent 83c2d95 commit 8e02ad0

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/libcore/option.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -632,6 +632,76 @@ impl<T> Option<T> {
632632
}
633633
}
634634

635+
/////////////////////////////////////////////////////////////////////////
636+
// Entry-like operations to insert if None and return a reference
637+
/////////////////////////////////////////////////////////////////////////
638+
639+
/// Inserts `v` into the option if it is `None`, then
640+
/// returns a mutable reference to the contained value.
641+
///
642+
/// # Examples
643+
///
644+
/// ```
645+
/// #![feature(option_entry)]
646+
///
647+
/// let mut x = None;
648+
///
649+
/// {
650+
/// let y: &mut u32 = x.get_or_insert(5);
651+
/// assert_eq!(y, &5);
652+
///
653+
/// *y = 7;
654+
/// }
655+
///
656+
/// assert_eq!(x, Some(7));
657+
/// ```
658+
#[inline]
659+
#[unstable(feature = "option_entry", issue = "39288")]
660+
pub fn get_or_insert(&mut self, v: T) -> &mut T {
661+
match *self {
662+
None => *self = Some(v),
663+
_ => (),
664+
}
665+
666+
match *self {
667+
Some(ref mut v) => v,
668+
_ => unreachable!(),
669+
}
670+
}
671+
672+
/// Inserts a value computed from `f` into the option if it is `None`, then
673+
/// returns a mutable reference to the contained value.
674+
///
675+
/// # Examples
676+
///
677+
/// ```
678+
/// #![feature(option_entry)]
679+
///
680+
/// let mut x = None;
681+
///
682+
/// {
683+
/// let y: &mut u32 = x.get_or_insert_with(|| 5);
684+
/// assert_eq!(y, &5);
685+
///
686+
/// *y = 7;
687+
/// }
688+
///
689+
/// assert_eq!(x, Some(7));
690+
/// ```
691+
#[inline]
692+
#[unstable(feature = "option_entry", issue = "39288")]
693+
pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
694+
match *self {
695+
None => *self = Some(f()),
696+
_ => (),
697+
}
698+
699+
match *self {
700+
Some(ref mut v) => v,
701+
_ => unreachable!(),
702+
}
703+
}
704+
635705
/////////////////////////////////////////////////////////////////////////
636706
// Misc
637707
/////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)