Skip to content

Commit ebc70e2

Browse files
authored
Rollup merge of #56796 - KrishnaSannasi:try_from_impl_change, r=shepmaster
Change bounds on `TryFrom` blanket impl to use `Into` instead of `From` This is from this [comment](#33417 (comment)) I made. This will expand the impls available for `TryFrom` and `TryInto`, without losing anything in the process.
2 parents e730697 + ea68b3f commit ebc70e2

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

src/libcore/convert.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -463,11 +463,11 @@ impl<T, U> TryInto<U> for T where U: TryFrom<T>
463463
// Infallible conversions are semantically equivalent to fallible conversions
464464
// with an uninhabited error type.
465465
#[unstable(feature = "try_from", issue = "33417")]
466-
impl<T, U> TryFrom<U> for T where T: From<U> {
466+
impl<T, U> TryFrom<U> for T where U: Into<T> {
467467
type Error = !;
468468

469469
fn try_from(value: U) -> Result<Self, Self::Error> {
470-
Ok(T::from(value))
470+
Ok(U::into(value))
471471
}
472472
}
473473

src/test/run-pass/try_from.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// This test relies on `TryFrom` being blanket impl for all `T: Into`
2+
// and `TryInto` being blanket impl for all `U: TryFrom`
3+
4+
// This test was added to show the motivation for doing this
5+
// over `TryFrom` being blanket impl for all `T: From`
6+
7+
#![feature(try_from, never_type)]
8+
9+
use std::convert::TryInto;
10+
11+
struct Foo<T> {
12+
t: T,
13+
}
14+
15+
// This fails to compile due to coherence restrictions
16+
// as of Rust version 1.32.x, therefore it could not be used
17+
// instead of the `Into` version of the impl, and serves as
18+
// motivation for a blanket impl for all `T: Into`, instead
19+
// of a blanket impl for all `T: From`
20+
/*
21+
impl<T> From<Foo<T>> for Box<T> {
22+
fn from(foo: Foo<T>) -> Box<T> {
23+
Box::new(foo.t)
24+
}
25+
}
26+
*/
27+
28+
impl<T> Into<Vec<T>> for Foo<T> {
29+
fn into(self) -> Vec<T> {
30+
vec![self.t]
31+
}
32+
}
33+
34+
pub fn main() {
35+
let _: Result<Vec<i32>, !> = Foo { t: 10 }.try_into();
36+
}
37+

src/test/ui/e0119/conflict-with-std.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ LL | impl TryFrom<X> for X { //~ ERROR conflicting implementations
2525
|
2626
= note: conflicting implementation in crate `core`:
2727
- impl<T, U> std::convert::TryFrom<U> for T
28-
where T: std::convert::From<U>;
28+
where U: std::convert::Into<T>;
2929

3030
error: aborting due to 3 previous errors
3131

0 commit comments

Comments
 (0)