4 ms·
What does `erase T` mean here? "We don't deref it so don't worry about the type, just erase it?"
by eximius 3y ago
What does `erase T` mean here? "We don't deref it so don't worry about the type, just erase it?"
- jcranmer 3y agoNormally, if you have generics, Rust makes copies of the function (/struct/enum/etc.) (aka "monomorphization"), one for each type that you use with it. The idea is to have a generic function but only one copy of the function, presumably because none of the code actually relies on the details of T.
- TheCoreh 3y agoIsn't this just `&dyn Trait`? Would it be a stack allocated, owning version of that, that can be moved? A pure `dyn Trait`?
- Ericson2314 3y agoNo. &mut dyn Foo is sugar for something like struct DynFoo<erase T> { vtable: &mut VTableFoo<T> ptr: &mut T } This is the underlying feature. `dyn` is a bit of an ad-hoc hack around not having this feature.
- eximius 3y agoI wonder if we really need an explicit syntax or if the compiler just need to disable monomorphization for functions that don't use the interior type e.g., only passing around references like this example. Without trait bounds there isn't much you can do with it anyway besides generic code like this. I guess the question is 'does Rust emit' or elide an unused generic function with unused interior types?
- Ericson2314 3y agoExplicit syntax is much better. "Just infer it" means we have to trace entire call graphs, because we have to know if our callees need monomorphization in order to know if we need monomorphization.
- jcranmer 3y agoIt's... not the most compelling feature in the world. The main use case I think I see is slightly easing the burden of writing external function signatures for a function that passes a user-definable type to a function callback parameter like qsort does. But there's relatively few of those functions in existence, and often times, you want a more ergonomic function definition anyways (see e.g. https://news.ycombinator.com/item?id=39267277 https://news.ycombinator.com/item?id=39267277 for qsort). The other major use case is if you've got something like a Vec<T> where several of the helper methods can be erasable. But it's already possible to do this with helper functions--the standard library takes advantage of it--so it's not entirely clear that you need a language-level feature for this use case.
- ithkuil 3y agoPolymorphic type erasure is the technique where the type is only used during type checking but has no impact on the generated code, namely the compiler doesn't emit specialized code for each instance of the type.