Skip to content

Commit fee3088

Browse files
committed
Improve Option::cloned method to allow mutable references
1 parent 86dde9b commit fee3088

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/libcore/option.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141

142142
use iter::{FromIterator, FusedIterator};
143143
use mem;
144+
use ops::Deref;
144145

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

645-
impl<'a, T: Clone> Option<&'a T> {
646+
impl<T: Clone, D: Deref<Target = T>> Option<D> {
646647
/// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
647648
/// option.
648649
#[stable(feature = "rust1", since = "1.0.0")]

src/libcoretest/option.rs

+8
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,8 @@ fn test_cloned() {
254254
let val = 1;
255255
let val_ref = &val;
256256
let opt_none: Option<&'static u32> = None;
257+
let mut opt_mut = Some(val);
258+
let opt_box: Option<Box<u32>> = Some(Box::new(val));
257259
let opt_ref = Some(&val);
258260
let opt_ref_ref = Some(&val_ref);
259261

@@ -269,4 +271,10 @@ fn test_cloned() {
269271
assert_eq!(opt_ref_ref.clone(), Some(&val_ref));
270272
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val));
271273
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1));
274+
275+
// Mutable ref works
276+
assert_eq!(opt_mut.as_mut().cloned(), Some(1));
277+
278+
// Deep Deref works
279+
assert_eq!(opt_box.cloned(), Some(1));
272280
}

0 commit comments

Comments
 (0)