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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With