I have an API which wants &[T] to represent a slice of things to sort.
I am indirectly sorting the indices for the actual data, so just want a &[usize] containing 0..len as the starting values.
Weirdly (to me at least) I could not achieve this with any shorthand syntax like:
(0..len)– Type mismatch [E0308] expected&[usize], but foundRange<usize>&(0..len)– expected&[usize], found&Range<usize>[0..len]– Type mismatch [E0308] expected&[usize], but found[Range<usize>; 1]&*[0..len]– error[E0614]: type[std::ops::Range<usize>; 1]cannot be dereferenced&[0..len]– ^ expected&usize, found&Range<usize>
The best I could come up with was: &Vec::from_iter(0..len).as_slice() but is this really the neatest/most idiomatic way to achieve this? Could there not be a functional slice which achieves this without an allocation?
>Solution :
This is pretty close to the most idiomatic way to express this, yes. If the context clearly wants a slice then you can shorten it to &Vec::from_iter(0..len) since Vec auto-derefs to a slice.
Otherwise, the other idiomatic way I can think of to express this would be &(0..len).collect::<Vec<_>>() which is slightly longer and requires the ugly turbofish to specify the collection type.