On Thu, Sep 5, 2013 at 9:29 AM, David Renshaw <[email protected]> wrote: > Hi, > > When I try to compile the below program, why do I get a "conflicting > implementations" error? I do not define any implementations of Bar, so > the parameterized impl of Foo should never get instantiated, right? > > ------------------- > > trait Foo { > fn foo() -> Self; > } > > trait Bar : std::num::Zero { } > > impl <T : Bar> Foo for T { > fn foo() -> T { > std::num::Zero::zero() > } > } > > impl Foo for u16 { > fn foo () -> u16 { > 100 > } > } > > fn main() { > > // should be 100 > let x : u16 = Foo::foo(); > printfln!("%s", x); > > } > > // error: conflicting implementations for trait `Foo` > > ------------------ >
The reason is that there is no guarantee that you will never use this code in a context where another module defines an impl of Bar for u16. In that scenario, you would have two different impls of Foo for u16, and no way to disambiguate. In Haskell, this is called the "overlapping instances" problem; it happens because traits in Rust, and type classes in Haskell, are open rather than closed (when you define a trait, you don't have any way of knowing all the impls of it for a particular type). > > When I asked about this on IRC, cmr indicated that this is probably > the intended behavior of rustc, but that most people want to change > it. Is that true, and when can we expect a fix? I'm not sure that most people want to change it. Handling the issue in general is quite subtle (see http://web.cecs.pdx.edu/~jgmorris/pubs/morris-icfp2010-instances.pdf ). One workaround is to use newtypes: struct Wrapper<T> { x: T } ... impl <T: Bar> Foo for Wrapper<T> { ... and then there's no ambiguity. Cheers, Tim -- Tim Chevalier * http://catamorphism.org/ * Often in error, never in doubt "Being queer is not about a right to privacy; it is about the freedom to be public, to just be who we are." -- anonymous, June 1990 _______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
