Deref coercion not working for Box<Trait>
The following fails to compile:
trait Trait {}
fn takes_ref(t: &Trait) {}
fn takes_box(t: Box<Trait>) {
takes_ref(&t)
}
fn main() { }
with
<anon>:5:15: 5:17 error: the trait `Trait` is not implemented for the type `Box<Trait>` [E0277]
<anon>:5 takes_ref(&t)
^~
despite the Deref implementation here.
I believe this should work based on the RFC.
cc @nick29581 @wycats
Aaron Turon at 2015-02-11 23:32:35
Bump!
emberian at 2015-06-09 19:17:24
Triage: today, this complains about a lack of
'static, and I'm not 100% sure how to fix it; I thought adding+ 'staticwould, but it doesn't seem to help.Steve Klabnik at 2017-01-03 20:03:37
I also encountered this bug while trying to iterate over boxed trait objects and posted to the user forum.
Michael Bryan at 2018-01-07 23:45:55
This came up again today.
Based on my reading, the unsize cooersion is only applying to the first level when it should pass through Deref cooersion as well.
Crystal Durham at 2018-10-25 18:27:08
Triage: no change
Maayan Hanin at 2022-03-23 06:19:44
This version seems to compile
trait Trait {} fn takes_ref(t: &dyn Trait) {} fn takes_box(t: Box<dyn Trait>) { takes_ref(&*t) }nielsle at 2022-03-23 07:10:24
@nielsle the problem is that
takes_ref(&t)won't compile even thoughtdereferences todyn Trait, which is what you would expect according to the deref coersion rules.Michael Bryan at 2022-03-23 14:30:16