And even with the original code, that specialization does kick in, meaning that there is no allocation or deallocation. It seems to be just that the loop can't be optimised away.
Example:
pub fn iter_thru(v: usize, slice: &mut [u32]) {
assert!(slice.len() > 42);
assert!(slice.len() < v);
for item in 0..v {
if item == 42 {
slice[42] = 17;
// With a `return;` added here, the function suddenly is
// just as optimised as the one below.
}
}
}
pub fn iter_thru_2(v: usize, slice: &mut [u32]) {
assert!(slice.len() > 42);
assert!(slice.len() < v);
slice[42] = 17;
}
(Godbolt)