How should you do pointer arithmetic in Rust?

后端 未结 1 1340
清歌不尽
清歌不尽 2021-02-11 12:57

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:57

    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)
提交回复
热议问题