You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Output: (Identical in rustc 1.36.0 (a53f9df 2019-07-03) and rustc 1.38.0-nightly (78ca1bd 2019-07-08).)
error[E0277]: the trait bound `&std::string::String:SomeTrait` is not satisfied
--> a.rs:12:5
|
12 | takes_type_parameter(&string);// Error
| ^^^^^^^^^^^^^^^^^^^^ the trait `SomeTrait` is not implemented for `&std::string::String`
|
note: required by `takes_type_parameter`
--> a.rs:3:1
|
3 | fn takes_type_parameter<T>(_:T) where T:SomeTrait{}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
In the takes_str(&string) call, the type of the _x parameter is known to be &str. &String can be coerced through auto-deref.
In the takes_type_parameter(&string) call, I imagine that trait resolution finds two solution (the _x parameter is either &str or char) but neither of them match with &string directly, so trait resolution emits an error. Presumably, coercion are only attempted in a later phase of compilation.
Is there a language design reason it has to be this way, or could we make programs like the above valid? (It then “only” be a matter of compiler implementation.)
Note that we do not perform coercions when matching traits (except for receivers, see below). If there is an impl for some type U, and T coerces to U, that does not constitute an implementation for T. For example, the following will not type check, even though it is OK to coerce t to &T and there is an impl for &T:
structT;traitTrait{}fnfoo<X:Trait>(t:X){}impl<'a>Traitfor&'aT{}fnmain(){let t:&mutT = &mutT;foo(t);//~ ERROR failed to find an implementation of trait Trait for &mut T}
Activity
abonander commentedon Jul 10, 2019
Related to #39801? (Similar situations it seems, like trait resolution should attempt deref coercion before erroring)
ldm0 commentedon May 2, 2020
@abonander @SimonSapin I guess this is the expected behaviour? Check RFC401
It's more like a diagnostic issue to me.
Rollup merge of rust-lang#72456 - ldm0:dereftrait, r=estebank