-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
core: Implement From<T> for Option<T> #33170
Conversation
r? @aturon (rust_highfive has picked a reviewer for you, use r? to override) |
I posted about this on internals a couple of months ago, but forgot to submit a PR to see what the maintainers think. |
89d7cd1
to
2b7c778
Compare
I added a commit changing the This allows writing code like
instead of requiring an additional
(Thanks to @sfackler for mentioning those APIs on the internals discussion!) |
This was also discussed here: rust-lang/rfcs#1402 |
@killercup oh thanks for that link! I'm glad I'm not the only person thinking down these lines. I wondered if this requires a full-blown RFC. It falls under small library additions, but is possibly a bit controversial and so could warrant the discussion period. |
This allows improved ergonomics for functions that have optional parameters: instead of taking `Option<T>`, they can have a type parameter bounded by `Into<Option<T>>`. That way, a value of type `T` can be passed directly without being wrapped by `Some`. As an example, a function fn foo<T>(required: i32, optional: T) -> i32 where T: Into<Option<i32>> { required + optional.into().unwrap_or(0) } can be called as `foo(2, None)` or as `foo(2, 3)`. Refs rust-lang/rfcs#1402
This allows writing code like stream.set_read_timeout(Duration::from_millis(200)); instead of requiring an additional `Some` wrapping the duration as is currently the case: stream.set_read_timeout(Some(Duration::from_millis(200)));
f061147
to
c7cd275
Compare
This behaves badly with nested options: Suppose you have a function
and you call it with
then it is unclear whether you mean Not sure how relevant this is, but I could imagine this popping up in some generic context. |
The libs team discussed this during triage the other day and the conclusion was that we don't want to do this at this time. The lang team has also been discussing the possibility of optional arguments recently (e.g. they are welcoming RFCs), and we wouldn't want the library side to conflict with the language side of these APIs. Thanks though for the PR @kamalmarhubi! |
This allows improved ergonomics for functions that have optional
parameters: instead of taking
Option<T>
, they can have a typeparameter bounded by
Into<Option<T>>
. That way, a value of typeT
can be passed directly without being wrapped by
Some
.As an example, a function
can be called as
foo(2, None)
or asfoo(2, 3)
.Refs rust-lang/rfcs#1402