Skip to content

Change bounds on TryFrom blanket impl to use Into instead of From #56796

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

Merged
merged 6 commits into from
Jan 21, 2019
Merged
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
4 changes: 2 additions & 2 deletions src/libcore/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,11 @@ impl<T, U> TryInto<U> for T where U: TryFrom<T>
// Infallible conversions are semantically equivalent to fallible conversions
// with an uninhabited error type.
#[unstable(feature = "try_from", issue = "33417")]
impl<T, U> TryFrom<U> for T where T: From<U> {
impl<T, U> TryFrom<U> for T where U: Into<T> {
type Error = !;

fn try_from(value: U) -> Result<Self, Self::Error> {
Ok(T::from(value))
Ok(U::into(value))
}
}

Expand Down
37 changes: 37 additions & 0 deletions src/test/run-pass/try_from.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// This test relies on `TryFrom` being blanket impl for all `T: Into`
// and `TryInto` being blanket impl for all `U: TryFrom`

// This test was added to show the motivation for doing this
// over `TryFrom` being blanket impl for all `T: From`

#![feature(try_from, never_type)]

use std::convert::TryInto;

struct Foo<T> {
t: T,
}

// This fails to compile due to coherence restrictions
// as of Rust version 1.32.x, therefore it could not be used
// instead of the `Into` version of the impl, and serves as
// motivation for a blanket impl for all `T: Into`, instead
// of a blanket impl for all `T: From`
/*
impl<T> From<Foo<T>> for Box<T> {
fn from(foo: Foo<T>) -> Box<T> {
Box::new(foo.t)
}
}
*/

impl<T> Into<Vec<T>> for Foo<T> {
fn into(self) -> Vec<T> {
vec![self.t]
}
}

pub fn main() {
let _: Result<Vec<i32>, !> = Foo { t: 10 }.try_into();
}

2 changes: 1 addition & 1 deletion src/test/ui/e0119/conflict-with-std.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ LL | impl TryFrom<X> for X { //~ ERROR conflicting implementations
|
= note: conflicting implementation in crate `core`:
- impl<T, U> std::convert::TryFrom<U> for T
where T: std::convert::From<U>;
where U: std::convert::Into<T>;

error: aborting due to 3 previous errors

Expand Down