|
|
Log in / Subscribe / Register

Existential types in Rust

Existential types in Rust

Posted May 13, 2024 16:05 UTC (Mon) by DanilaBerezin (guest, #168271)
Parent article: Existential types in Rust

Maybe I'm just way in over my head and don't understand anything, but what use case do "existential types" have outside of the "self" key-word? Which is as far as I'm aware is already implemented? Or is this feature just an optimization of the "self" keyword, somehow removing the need for trait objects when implementing the keyword?

If the implementation of a trait takes in a trait as it's argument, that argument can either refer to the same implementation, or some other implementation of the trait. In the former case, this is what "self" does, and this works because when you call a function in a trait, you are also guaranteed to have the same implementation of the trait in the exact same scope as the site of the call. In the latter case, you have to explicitly specify the concrete implementation that the implementation actually takes so that the compiler can enforce what concrete type is actually passed in. Otherwise the caller could pass in arbitrary implementations of the same trait to the implementation and that would obviously not work. But at that point, the caller has to both know and define the concrete type for the trait they pass into the implementation. At that point, why use traits at all, why not just use a concrete type?

There is a use case for passing in traits when you want a "generic" function that accepts any trait implementation and only uses the constructs exposed by the trait, but this is the exact opposite of an "existential type" then. The "generic" type passed in is not coerced into some concrete type, it is kept generic, quite literally the "universally-quantified" type mentioned earlier. So once again, I don't see a use case there. Like I said though, maybe I'm just completely not understanding what the point of this type is.


to post comments

Existential types in Rust

Posted May 13, 2024 16:14 UTC (Mon) by DanilaBerezin (guest, #168271) [Link]

Actually I'm realizing that maybe the use case here is specifically tailored to functions returning traits rather than functions taking in traits as arguments, in which case yes, I can definitely see a magnitude of use cases, pretty much all of them being just generics (as others have already pointed out in the comments).


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds