How should you do pointer arithmetic in Rust?

后端 未结 1 823
北荒
北荒 2021-02-11 13:28

I know the answer is \"you shouldn\'t\"... but for the sake of argument, how should you do it?

For example, if you wanted to write an alternative to Vec&l

相关标签:
1条回答
  • 2021-02-11 13:50

    Pointers have an offset method for pointer arithmetic.

    fn main() {
        let items = [1usize, 2, 3, 4];
    
        let ptr = &items[1] as *const usize;
    
        println!("{}", unsafe { *ptr });
        println!("{}", unsafe { *ptr.offset(-1) });
        println!("{}", unsafe { *ptr.offset(1) });
    }
    

    Output

    2
    1
    3
    

    https://doc.rust-lang.org/nightly/book/first-edition/unsafe.html

    0 讨论(0)
提交回复
热议问题