Skip to content

#[deriving()], concrete implementations and problems with traits #15923

Closed
@seb-m

Description

@seb-m

The following code fails to compile:

pub trait FooTrait {
    fn new() -> Self;
}

pub struct Foo {
    elem: int
}

impl FooTrait for Foo {
    fn new() -> Foo {
        Foo {
            elem: 42
        }
    }
}

pub struct SFoo<T> {
    elem: int
}

impl<T: FooTrait> SFoo<T> {
    pub fn new() -> SFoo<T> {
        SFoo {
            elem: 42
        }
    }
}

impl<T: FooTrait> Clone for SFoo<T> {
    fn clone(&self) -> SFoo<T> {
        SFoo {
            elem: self.elem
        }
    }
}

#[deriving(Clone)]
struct Bar<T> {
    elem: SFoo<T>
}

impl<T: FooTrait> Bar<T> {
    fn new() -> Bar<T> {
        Bar {
            elem: SFoo::new()
        }
    }
}

fn main() {
    let bar: Bar<Foo> = Bar::new();
}

With the following error:

r.rs:41:5: 41:18 error: failed to find an implementation of trait FooTrait for T
r.rs:41     elem: SFoo<T>
            ^~~~~~~~~~~~~
note: in expansion of #[deriving]

Whereas when #[deriving(Clone)] is used on SFoo instead of providing a concrete implementation for the Clone trait it compiles correctly:

pub trait FooTrait {
    fn new() -> Self;
}

pub struct Foo {
    elem: int
}

impl FooTrait for Foo {
    fn new() -> Foo {
        Foo {
            elem: 42
        }
    }
}

#[deriving(Clone)]
pub struct SFoo<T> {
    elem: int
}

impl<T: FooTrait> SFoo<T> {
    pub fn new() -> SFoo<T> {
        SFoo {
            elem: 42
        }
    }
}

#[deriving(Clone)]
struct Bar<T> {
    elem: SFoo<T>
}

impl<T: FooTrait> Bar<T> {
    fn new() -> Bar<T> {
        Bar {
            elem: SFoo::new()
        }
    }
}

fn main() {
    let bar: Bar<Foo> = Bar::new();
}

It seems to me that the code in the first case should also compile without error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions