Idea: Named sets of impls


#1

I would like to have more control over impls in Rust in situations such as when types and traits are defined in separate crates that does not know about each other. Furthermore, I would like to see this taken a step further to a kind of closed family of associated types, where each member type of a “family” can be inferred from all other members.

Currently the only way to implement something, when both the type and trait is external, is to wrap the types in new ones. I think this is too limited.

Found this comment:

Have anyone thought of named sets of impls? Instead of giving each impl a different name, you could give multiple ones the same name.

impl Foo1 for Bar1 as Baz { ... }
impl Foo2 for Bar2 as Baz { ... }
                      ^--- named set

In user code:

fn main() {
    use Baz; // put methods of `Bar1` and `Bar2` into scope
    ...
}

This could be extended with a new abstraction that associates types together in a closed family:

family Foo {
    type Bar;
    type Baz;

    fn foo(a: Bar) -> Baz { ... }
}

struct MyBar(u32);

impl Foo as Qaz {
    type Bar = MyBar;
    type Baz = ...;

    fn foo(a: Bar) -> Baz { ... }
}

fn main() {
    use Qaz;

    let a = foo(MyBar(2));
}

The idea is to abstract at some higher level of library functionality. Instead of adding trait A and B in scope, I want to program in the way I think about libraries: Library A is a backend for B etc. Also, I don’t want to depend on library authors to opt-in to use a common abstraction.

For example: Gfx has OpenGL, Metal and DirectX backends. Each backend has a complex set of types that are closed, but currently you have to add a phantom R: gfx::Resources everywhere.

I want to write:

extern crate gfx_device_gl;

use gfx_device_gl::GlGfx; // Everything I need

fn main() {
    let window = ...;
    let (frame_buffer, factory) = window.gl_init(); // method added by `GlGfx`
    ...
}

#2

There might be an alternative solution https://github.com/PistonDevelopers/backend/issues/20


#3

(oops, I didn’t notice that it’s an old topic. Sorry for bumping it unnecessarily)


#4

The idea with using named sets is to both solve the coherence problem and get a controlled way of importing a whole set of traits.