Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Idiomatic Rust way of making a slice of contiguous integers?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • (0..len) – Type mismatch [E0308] expected &[usize], but found Range<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading