Answer#
In C one pointer type does four jobs: it owns memory, it borrows memory, it may be null, and it may point to many items. Rust has a separate type for each job, and the compiler checks the rules that C leaves to the programmer. Translate by asking which job each pointer does.
| C | Rust | Notes |
|---|---|---|
T *p = malloc(sizeof *p) ... free(p) | Box<T> | Freed when it goes out of scope; no free |
T *a = malloc(n * sizeof *a) ... free(a) | Vec<T> | Grows with push; knows its length |
char *s (owned text) | String | UTF-8, owns its bytes |
const T *p (borrowed, read only) | &T | Checked: cannot outlive the value |
T *p (borrowed, changed through) | &mut T | Only one at a time |
const T *a, size_t n | &[T] | A slice carries its length |
pointer that may be NULL | Option<&T>, Option<Box<T>> | None is the null; same size as a pointer |
T *next in a linked structure that owns its tail | Option<Box<Node>> | |
void * | a generic type parameter, or a trait object | |
T * across a C interface | *const T, *mut T | Raw pointers: using them needs unsafe |
This program shows the four common rewrites. It was compiled and run with rustc 1.93.0.
// C: int *buf = malloc(n * sizeof *buf); ... free(buf);
// Rust: a Vec owns the memory and frees it when it goes out of scope.
fn sum_squares(n: usize) -> u64 {
let mut buf: Vec<u64> = Vec::with_capacity(n);
for i in 0..n as u64 {
buf.push(i * i);
}
buf.iter().sum()
} // buf is freed here; there is no free() to forget
// C: int *find(const int *a, size_t n, int x) returning a pointer or NULL
// Rust: a borrowed slice in, an Option out.
fn find(a: &[i32], x: i32) -> Option<&i32> {
a.iter().find(|&&v| v == x)
}
// C: void bump(int *p) { *p += 1; }
// Rust: a mutable reference, checked at compile time.
fn bump(p: &mut i32) {
*p += 1;
}
// C: struct node { int v; struct node *next; }; (a list that owns its tail)
// Rust: Option<Box<...>> is "a pointer that may be null and owns what it points to".
struct Node {
v: i32,
next: Option<Box<Node>>,
}
fn len(mut at: &Option<Box<Node>>) -> usize {
let mut n = 0;
while let Some(node) = at {
n += 1;
at = &node.next;
}
n
}
fn main() {
println!("{}", sum_squares(5));
let a = [3, 5, 7];
println!("{:?} {:?}", find(&a, 5), find(&a, 9));
let mut x = 1;
bump(&mut x);
println!("{x}");
let list = Some(Box::new(Node { v: 1, next: Some(Box::new(Node { v: 2, next: None })) }));
println!("{} {}", len(&list), list.as_ref().map(|n| n.v).unwrap_or(0));
}30
Some(5) None
2
2 1Common mistakes#
- Translating every
T *to a raw pointer and wrapping the code inunsafe. That keeps C's problems; use the safe type that matches the job. - Porting pointer arithmetic literally. Iterate over a slice (
for x in &a) or use indices, which are bounds-checked. - Porting a doubly linked list or a graph directly. Owned back-pointers do not fit Rust's rules; use indices into a
Vec, orRc/Weakwhen sharing is real.
Related questions#
What replaces NULL checks?#
Option. The compiler will not let you use the value without handling None, so a missing check is a compile error instead of a crash.
What happens to pointer-and-length pairs?#
They become slices. A &[T] is a pointer and a length in one value, and indexing past the end stops the program with a clear panic instead of reading memory it does not own.
Sources#
- The Rust Book, "Understanding Ownership": https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
- The Rust Book, "Using Box<T> to Point to Data on the Heap": https://doc.rust-lang.org/book/ch15-01-box.html