Skip to content

Commit

Permalink
Rollup merge of rust-lang#34828 - seanmonstar:into-opton, r=alexcrichton
Browse files Browse the repository at this point in the history
core: impl From<T> for Option<T>

First, the semantics of this `impl` seem spot on. If I have a value `T`, and I wish to make a `Option<T>`, then `Option::from(val)` should always give `Some(val)`.

Second, this allows improvement for several APIs that currently take `Option<T>` as arguments. Consider:

```rust
fn set_read_timeout(&mut self, timeout: Option<u32>) {
    // ...
}

x.set_read_timeout(Some(30));
x.set_read_timeout(Some(10));
x.set_read_timeout(None);
```

With this `impl`:

```rust
fn set_read_timeout<T: Into<Option<u32>>>(&mut self, timeout: T) {
    let timeout = timeout.into();
    // ...
}

x.set_read_timeout(30);
x.set_read_timeout(10);
x.set_read_timeout(Some(10)); // backwards compatible
x.set_read_timeout(None);
```

The change to those methods aren't included, but could be modified later.

r? @sfackler
  • Loading branch information
GuillaumeGomez authored Jul 21, 2016
2 parents e7c822c + fbfee42 commit bcbe27c
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@
use self::Option::*;

use clone::Clone;
use convert::From;
use default::Default;
use iter::ExactSizeIterator;
use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
Expand Down Expand Up @@ -754,6 +755,13 @@ impl<'a, T> IntoIterator for &'a mut Option<T> {
}
}

#[stable(since = "1.12.0", feature = "option_from")]
impl<T> From<T> for Option<T> {
fn from(val: T) -> Option<T> {
Some(val)
}
}

/////////////////////////////////////////////////////////////////////////////
// The Option Iterators
/////////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit bcbe27c

Please sign in to comment.