Scala'owe ATM:
abstract class SeqBuffer extends Buffer {
type U
type T <: Seq[U]
def length = element.length
}
... w Rust są, o ile dobrze rozumiem, zwyczajnymi traitami:
trait SeqBuffer {
type U;
type T: Seq<Self::U>;
}
(w rustowej terminologii U
oraz T
są nazwane associated type
.)
To, co jest teraz implementowane dodatkowo, to możliwość stworzenia generic associated type
:
trait SeqBuffer {
type T<U>: Seq<U>;
}
// SeqBuffer::T = type constructor
Taki pozornie prosty ficzer umożliwia np. zbudowanie traitu pozwalającego na wybór między rodzajem smart-wskaźnika:
trait PointerFamily {
type Pointer<T>: Deref<Target = T>;
}
// Arc = reference counted, z obsługą wielowątkowości
struct ArcFamily;
impl PointerFamily for ArcFamily {
type Pointer<T> = Arc<T>;
}
// Rc = reference counted, bez obsługi wielowątkowości
struct RcFamily;
impl PointerFamily for RcFamily {
type Pointer<T> = Rc<T>;
}
// Struktura jest generyczna nad typem wskaźnika - użytkownik może wybrać między `ArcFamily` albo `RcFamily`, i
// otrzymać odpowiednio `Arc<HashMap<...>>` lub `Rc<HashMap<...>>`
struct ConcurrentMap<P: PointerFamily> {
map: P::Pointer<HashMap<String, String>>,
}