Using `impl Trait` for monomorphized heterogenous collections

Anonymous enums wouldn't be the right solution here. enum impl Trait was sugar that evaluated to a concrete type known to the compiler, but opaque to the user. This was because it was only used as a return type. But one of the design goals for [impl Trait; N] is the ability to pass it to accepting functions.

let mut x: [impl Debug; 3] = ["these", 3u16, false];
modifies_x(&mut x); // containes: x[1] = true

If modifies_x was a virutal function, the scope would not be able to determine what the modifications would be. x[1] = expr would need to shadow x into a new variable in the owners scope, move all the parts of x except for x[1], then store expr into x[1].


Tuple Trait with Enums Spitballing

If Anon Enums did exist, There could be a auto implemented Tuple trait with get functions

trait Tuple {
    type Output; // Enum where references to all field types are variants 

    const fn size(&self) -> usize;
    const fn get(&self, index: usize) -> Result<Output>;
}

With a tuple trait, the variably sized tuples could be passed into functions using generics.

fn receiver<T, O>(tuple : T) 
where T : impl Tuple<Output = O>,
      O : Display;

And since enums would inherit the traits of their variants, you could iterate through them without dynamic dispatch.

for enum_of_refs in tuple.iter() {
    println!("{:?}", enum_of_refs);
}

Yeah, it needs a heterogeneous type, like you mention under the ▼.

I could imagine something like this, though:

let x: impl Bikeshed<dyn Debug, 3> = ("these", 3u16, false);
1 Like

Note: renamed the thread to hopefully better capture what I was after

It sounds like you want variadic generics?

As in, you want to iterate over heterogeneous collections of objects that implement the same trait, without using dynamic dispatch. That sounds like a variadics use case to me.

2 Likes

@PoignardAzur great! I'll look into it more

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.