Will this ever be possible? (Generic Trait parameters)


#1
	fn get_as_trait_ref<trait T>(&mut self, id: Enum) -> &mut T where /* typeof(self.{a,b,c,d}): T */ {
		use self::Enum::*;
		match id {
			A => &mut self.a,
			B => &mut self.b,
			C => &mut self.c,
			D => &mut self.d,
		}
	}

(the where clause is pseudo-code.)

Currently I have to use a macro to generate such a method for every trait I want to support…

I know this is probably not the best example to demonstrate a need for generic Trait parameters, but are there any plans in this direction?


#2

I don’t understand what this is supposed to do. What is the return type T?


#3

T is not a type but a trait, and the return type is a (mutable) trait ref.


#4

If I’m understanding this right, it looks like generic function overloading, and generalizes beyond just trait objects. It’s sort of like the Into::into() method except T is a compile-time restricted multi-choice.

Caller picks a T to call with, but the T is restricted to be one of available types (in this example, matching the type of one of the fields). The body of the fn is then required to return that type, which means you’d need to match on typeof(T) essentially. If matching on the type of T statically, you’d need some syntax support, e.g. (making stuff up):

T: i32 -> &mut self.a,
T: String -> &mut self.b,
...

If you were to allow this dynamically, then you’d need a bit of reflection support to expose typeof(T) at runtime.

There would need to be a way to indicate the available T without leaking out internal details, such as fields.

I’m not aware of anything like this in the works.


#5

No, T is not the type of one of the fields, it’s a trait that the types of all the fields (those that could be returned) impl.


#6

Ah, I see. I think the gist of my reply still stands though - you want an overloaded but restricted T, except the restriction is where all fields impl the T. This means static type dispatch in the body isn’t needed and this forces a trait object indeed to erase the concrete type.