Pointer Types
Rust's pointers are one of its more unique and compelling features. Pointers are also one of the more confusing topics for newcomers to Rust. They can also be confusing for people coming from other languages that support pointers, such as C++.
An introduction
If you aren't familiar with the concept of pointers, here's a short introduction. Pointers are a very fundamental concept in systems programming languages, so it's important to understand them.
Pointer Basics
When you create a new variable binding, you're giving a name to a value that's stored at a particular location on the stack. (If you're not familiar with the heap vs. stack, please check out this Stack Overflow question, as the rest of this guide assumes you know the difference.) Like this:
fn main() { let x = 5; let y = 8; println!("x address: {:p}", &x); println!("y address: {:p}", &y); }
| variable | location | value |
|---|---|---|
| x | 0x7ffed0010e60 (varies) | 5 |
| y | 0x7ffed0010e64 (varies) | 8 |
See the difference? Rather than contain a value, the value of a pointer is a location in memory. In this case, the location of y. x and y have the type i32, but z has the type &i32. We can print this location using the {:p} format string:
fn main() { let x = 5; let y = 8; let z = &y; println!("&y address: {:p}", &y); // -> &y address: 0x7ffecbc161cc println!("z address: {:p}", z); // -> z address: 0x7ffecbc161cc }
Because i32 and &i32 are different types, we can't, for example, add them together:
fn main() { let x = 5; let y = 8; let z = &y; // unlioke this articale was written, it will cause error println!("{}", x + z); // version 1.51.0, -> 13 println!("{}", x + *z);// version 1.51.0, -> 13 println!("{}", x + &y);// version 1.51.0, -> 13 }
That's it! That's all pointers are: they point to some memory location. Not much else to them. Now that we've discussed the what of pointers, let's talk about the why.