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

How to convert range to slice in rust?

I want to create a slice of numbers within certain range in Rust. However, the following syntax does not seem to work, as the output is a slice of length 1, composed of a Range object.

let count = 10;
let slice = [0..count/2];

What’s the proper way to create a slice in Rust from a range?

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

>Solution :

You cannot create a slice directly from a range (unless you know an upper bound to the number of elements at compile time, in which case you can use an array), you have to use Vec:

let vec = Vec::from_iter(0..count/2);
let slice = vec.as_slice();
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