Is My Highly Unsafe Code Correct? In Place Mapping a Vector

Thanks to both of you! The explanation about the difference between [T] and &[T] was very helpful. I forgot at some point that those unsized types existed and in my mind &[T] was the slice, hence my confusion.

The confusion really was that you thought a &mut [T] would coerce to a *mut T. The slice type [T] is just a regular type; you can have a reference or a pointer to it, there's no "array to pointer decay" going on as in C. A reference-to-slice doesn't automatically become a pointer-to-element, so it doesn't lose information.

This "information" here is of course purely type-level; the numeric value of the pointer to the slice is exactly the same as a pointer to its first element, but whether it has type T or [T] matters a lot, because the function will drop whatever type it gets. If it gets a pointer to a slice, it will drop the whole slice. If it gets a pointer to an element, it will drop that element. There's no magic going on, this is exactly what you should expect.

1 Like

Yes, precisely. However, I disagree with your last sentence. I've been working in C++ again lately, so a type system that actually cares about types does feel like magic :rofl:

1 Like

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.