Search code examples
rustsliceoption-type

How to get subslice of Options instead of Option of subslice?


From documentation, get method, given a range, returns an Option of subslice which is None if range is out of bounds:

let v = [10, 40, 30];
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(0..4));

Is there a way to get a slice of Options instead, so v.get(0..4) would return a subslice with Some(10), Some(40), Some(30), None values?


Solution

  • You can't return a slice, because a slice always has to refer to a contiguous memory region with items of the exact same layout. Your storage doesn't store additional None before and after the values that an out of bounds slice could refer to, and neither do T and Option<T> always have the same layout, so a slice is out of the question.

    Instead you could create an iterator over Option<&T> that you can collect if you want to:

        let iter = (0..4).map(|i| v.get(i));
        let opt: Vec<Option<&i32>> = iter.collect();
        assert_eq!(opt, vec![Some(&10), Some(&40), Some(&30), None]);
    

    For Copy types it might be more efficient to copy the items instead of taking references for example with Option::copied