Search code examples
rustslicepointer-arithmetic

Minus operation for slices


How do I make to work the following code:

let arr: [u8; 3] = [1, 2, 3];
let x1: &[u8] = &arr[0..];
let x2: &[u8] = &arr[1..];
let d: isize = x2 - x1;

I have two slices into one vector and I want to know the difference between their start pointers (should be 1 in that example).


Solution

  • One of approaches is to convert pointers to slice contents to isize and do arithmetics on these values:

    let arr: [u8; 3] = [1, 2, 3];
    let x1: &[u8] = &arr[0..];
    let x2: &[u8] = &arr[1..];
    let d: isize = x2.as_ptr() as isize - x1.as_ptr() as isize;
    println!("{}", d);
    

    But I'm not sure how this would work if the address does not fit into isize.