Skip to content

A generic &X that implements trait Trait cannot be stored in a struct that is cast to Trait #10640

@erickt

Description

@erickt

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

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions