Skip to content

Improve Option::cloned method to allow mutable references #36137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@

use iter::{FromIterator, FusedIterator};
use mem;
use ops::Deref;

// Note that this is not a lang item per se, but it has a hidden dependency on
// `Iterator`, which is one. The compiler assumes that the `next` method of
Expand Down Expand Up @@ -642,7 +643,7 @@ impl<T> Option<T> {
}
}

impl<'a, T: Clone> Option<&'a T> {
impl<T: Clone, D: Deref<Target = T>> Option<D> {
/// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
/// option.
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
8 changes: 8 additions & 0 deletions src/libcoretest/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ fn test_cloned() {
let val = 1;
let val_ref = &val;
let opt_none: Option<&'static u32> = None;
let mut opt_mut = Some(val);
let opt_box: Option<Box<u32>> = Some(Box::new(val));
let opt_ref = Some(&val);
let opt_ref_ref = Some(&val_ref);

Expand All @@ -269,4 +271,10 @@ fn test_cloned() {
assert_eq!(opt_ref_ref.clone(), Some(&val_ref));
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val));
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1));

// Mutable ref works
assert_eq!(opt_mut.as_mut().cloned(), Some(1));

// Deep Deref works
assert_eq!(opt_box.cloned(), Some(1));
}