Skip to content

Instantly share code, notes, and snippets.

@brson
Created October 5, 2012 22:59
Show Gist options
  • Save brson/3842948 to your computer and use it in GitHub Desktop.
Save brson/3842948 to your computer and use it in GitHub Desktop.
## Dereferencing pointers
Rust uses the unary star operator (`*`) to access the contents of a box or pointer, similarly to C.
~~~
let managed = @10;
let owned = ~20;
let borrowed = &30;
let sum = *managed + *owned + *borrowed;
~~~
Dereferenced mutable pointers may appear on the left hand side of assignments, in which case the value they point to is modified.
~~~
let managed = @mut 10;
let owned = ~mut 20;
let borrowed = &mut 30;
let *managed = *owned + 10;
let *owned = *borrowed + 100;
let *borrowed = *managed + 1000;
~~~
Pointers have high operator precedence, but lower precedence than the dot operator used for field and method access. This can lead to some awkward code filled with parenthesis.
~~~
# struct Point { x: float, y: float }
# struct Rectangle { ... }
let start = @Point { x: 10f, y: 20f };
let end = ~Point { x: (*start).x + 100, y: (*start).y + 100 };
let rect = &Rectangle { ... };
let area = (*rect).area();
~~~
To combat this ugliness the dot operator performs _automatic pointer dereferencing_ on the receiver (the value on the left hand side of the dot), so in most cases dereferencing the receiver is not necessary.
~~~
let start = @Point { x: 10f, y: 20f };
let end = ~Point { x: start.x + 100, y: start.y + 100 };
let rect = &Rectangle { ... };
let area = rect.area();
~~~
Auto-dereferencing is performed through any number of pointers. If you felt inclined you could write something silly like
~~~
let point = &@~Point { x: 10f, y: 20f };
io::println(fmt!("%f", point.x));
~~~
The indexing operator (`[]`) is also auto-dereferencing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment