Pointer arithmetic in Rust

Yasuaki MORITA
Jul 26, 2017 · 1 min read

I tried Rust today.

First, I was interested in pointer arithmetic in Rust.

In C, we can compile pointer arithmetic.

<stddef.h>
int main() {
int tmp;
int *a = NULL;
int *b = &tmp;
printf("%td\n", a - b); // difference between two pointers
printf("%d\n", a < b); // compare between pointers
return 0;
}

Rust forbids pointer arithmetic but permits pointer comparison based memory address order relation.

fn main() {
let tmp = 0i32;
let a = &tmp as *const i32;
let b = &0 as *const i32;
//println!("{}", a - b); //compile error!!
println!("{}", a < b); // compare between two pointers
}

References and slices are never used as memory address.

References are implicitly replaced by dereferenced value as needed.

fn main() {
let tmp = 0i32;
let a = &tmp;
let b = &0i32;
println!(“{}”, a — b); // return 0
println!(“{}”, a == b); // return true
}

Comparison between two slices returns result based lexicographical order of content of slice.

fn main() {
let tmp = [0i32; 5];
let a = &tmp[0 .. 1];
let b = &tmp[1 .. 2];
// println!(“{}”, a — b); // compile error!!
println!(“{}”, a == b); // return true
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade