Centril / rfc-trait-parametric-polymorphism

Planning, scheming and designing of {-# LANGAUGE ConstraintKinds #-} for Rust
11 stars 0 forks source link

Turning a type into a trait? #9

Open Centril opened 6 years ago

Centril commented 6 years ago

What would this mean?

BTW, I don't know if this is in your list at all, but dyn turns a trait into a type, and I wonder if there should be a thing that turns a type into a trait a very boring trait that only matches the type

scottmcm commented 6 years ago

Here's my attempt at a rust translation of the place I end up using this the most in C#:

fn get_or_default<'a, type K, type T, type D, trait Tr>
    (h: &'a HashMap<K, T>, k: K, d: &'a D) -> &'a dyn Tr
    where T: Tr, D: Tr
{
    match h.entry(k) {
        Occupied(x) => x.value(),
        Vacant => d,
    }
}

So, supposing container traits, you could &dyn Stack from a Vec if you wanted, but you could also use Tr = bikeshed Vec<i32> to get a real Vec out.

Centril commented 6 years ago

Sidenote

You gave me an idea...! You've ensured that two possibly different types both implement the same trait without mentioning the trait. I wonder if that can be useful on its own?

MWE:

fn assert_both_same_trait<trait Tr, A: Tr, B: Tr>() {}

assert_both_same_trait::<Sync, i32, u32>();