What's `default fn()`?

in alloc::slice::hack::to_vec

This is part of the unstable feature of specialization.

1 Like

default is a keyword part of specialization. Specialization in Rust is highly unstable and still has soundness holes. So it won't be stabilised any time soon.

I see. Thanks for your patience!

In the concrete case at hand

you’ll see two implementations

impl<T: Clone> ConvertVec for T
impl<T: Copy> ConvertVec for T

The latter specializes the former. The default keyword here means that that’s a method that can be changed in the more specific, specializing implementations. This all is part of the internals of implementing the <[T]>::to_vec method; specialization on Copy is a common implementation strategy in the standard library in order to offer better optimization; though because stabilization isn’t a stable feature, it’s also only used for the purporse of optimization, and isn’t supposed to influence behavior in observable ways. (Though it can actually be observable, that’s only the case for types that don’t implement Copy + Clone properly, since usually you are supposed to make Clone behave identical to Copy in case both are implemented.)

The way that such a data copying method can be optimized for Copy types is that you don’t need to write a loop with .clone() calls anymore but can directly copy the whole memory contiguously using the more efficient approach of std::ptr::copy_nonoverlapping.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.