Return a trait reference from a trait
This code won't work:
pub trait Foo<T: ?Sized> { fn as_ref(&self) -> &T; }
pub trait Thing { fn hi(); }
struct Bar;
impl Thing for Bar {
fn hi() {
println!("Hi");
}
}
impl Foo<Thing> for Bar {
fn as_ref(&self) -> &Thing {
return self;
}
}
#[test]
fn test_action() {
let x = Bar;
x.as_ref().hi();
}
Why not?
The issue is that Thing
is not really Thing
, it is Thing + 'static
, so the error occurs:
<anon>:13:3: 15:4 error: method `as_ref` has an incompatible type for trait:
expected bound lifetime parameter ,
found concrete lifetime [E0053]
The correct implementation is:
fn as_ref<'a>(&'a self) -> &'a (Thing + 'static) {
return self;
}
Or, to be more generic, an arbitrary lifetime 'b
:
pub trait Foo<T: ?Sized> { fn as_ref(&self) -> &T; }
pub trait Thing { fn hi(&self); }
struct Bar;
impl Thing for Bar {
fn hi(&self) {
println!("Hi");
}
}
impl<'b> Foo<Thing + 'b> for Bar {
fn as_ref(&self) -> &(Thing + 'b) {
return self;
}
}
#[test]
fn test_action() {
let x = Bar;
x.as_ref().hi();
}