Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use step in Rust slice?

Tags:

slice

rust

In python, we can get subarray in odd indexes like:

odd = array[1::2]

Can we do this in Rust, using simple syntax or any traits? like:

let vec = vec![1; 10];
let sli = &vec[0.2.10];

The above code cannot pass the compile.

like image 412
Walker Avatar asked Sep 05 '25 00:09

Walker


2 Answers

Rust doesn't have this Python feature. However, you can apply a step size to any iterator by using the .step_by() method.

let v: Vec<i32> = (0..10).step_by(2).collect();
assert_eq!(v, vec![0, 2, 4, 6, 8]);

However, note that the step size must be positive, unlike Python, where a negative step size means to walk the list backwards. To reverse an iterator in Rust, you can usually use .rev().

let v2: Vec<i32> = v.into_iter().rev().collect();
assert_eq!(v2, vec![8, 6, 4, 2, 0]);

If you're using a tensor library, like ndarray, it'll have its own way of slicing with a step size, like this ndarray macro.

like image 149
Jason Orendorff Avatar answered Sep 07 '25 20:09

Jason Orendorff


No, a slice is

A dynamically-sized view into a contiguous sequence

You could collect references into the original slice into a Vec though:

let odd: Vec<&i32> = array.iter().step_by(2).collect();

But for many applications you don't even need to collect at all but can use the Iterator directly.

like image 36
cafce25 Avatar answered Sep 07 '25 21:09

cafce25