mozilla/rust — Issue #1718: RFC: Parameterizable self type in ifaces
Author: marijnh
Created: 2012-01-31 16:20:56+00:00
State: open
Labels: rfc

Currently, it is not possible to express, for example, that the `map` method of a `mappable` interface returns the same kind of container type as the input, but with its inner type changed to the output type of the mapping function.

At https://github.com/marijnh/rust/tree/self_tys , there's an implementation of an extension that allows the following:

```
iface S: mappable {
fn map

(fn(T) -> U) -> S

;
}

impl of mappable for [T] {
fn map

(fn(T) -> U) -> [U] { ... }
}
```

By prefixing the `iface` name with an ident and a colon, you provide an explicit name for the self type. This acts as a parameterized type with the same amount of parameters as the iface has (1 in the above case, can also be zero or more), that may appear in the method signatures to refer to the self type of the impl. This allows basic forms of Haskellisms like Monad and Functor to be expressed (in fact, the `mappable` above is a functor), but also comes in handy with simpler things.

Abstaction with bounded type parameters on such types currently only works when no new self types are introduced (you could map from a type to itself in a generic that has `>` params) -- which tirivally holds for non-parameterized self types. We could, somewhere in the far future, consider adding parameterized parameters (`: mappable

>` or similar) to allow more expressivity in this area.

Methods with self types in them can't be called on boxed iface values, since those hide the self type, and the result wouldn't be sanely typable (we could insert magic to automatically box the result, but this seems too weird and not immediately useful).