-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Closed
Labels
A-type-systemArea: Type systemArea: Type system
Description
I'm sorry for the bad title, if someone has one, please suggest it. I'm trying to create one generic type that implements a trait and store it in a structure and temporary wrapper of a trait, but unfortunately I'm hitting what I suspect is an invalid error. Here's an example with the error inlined in the comments:
trait Trait {
fn greet(&self);
}
struct X;
struct Y<T> { t: T }
impl Trait for X {
fn greet(&self) {
println!("X");
}
}
impl<T: Trait> Trait for Y<T> {
fn greet(&self) {
println!("Y");
self.t.greet();
}
}
fn foo<T: Trait>(t: T) {
let y = Y { t: t };
y.greet();
}
fn bar<T: Trait>(t: &T) {
let y = Y { t: t };
y.greet(); // error: failed to find an implementation of trait Trait for &T
}
fn baz(t: &Trait) {
let y = Y { t: t };
y.greet(); // error: failed to find an implementation of trait Trait for &Trait<no-bounds>
}
fn main() { }
I did find a workaround, where we add explicit implementations for the generic forms, as in:
impl<'a, T: Trait> Trait for &'a T {
fn greet(&self) { (*self).greet() }
}
impl<'a> Trait for &'a Trait {
fn greet(&self) { (*self).greet() }
}
But I thought Rust was able to automatically derive these implementations. I also ran into some problems trying to add these generic implementations to Iterator<T>
, so I'm not sure if that works in all circumstances.
Metadata
Metadata
Assignees
Labels
A-type-systemArea: Type systemArea: Type system