Foreword: Rust is still under development, and the language has changed a lot since this question was answered.
For one, @ pointer is about to be removed from the languages, replaced by the Gc and Rc smart pointers, both provided by the standard library.
Second, the syntax for the lifetimes is now &'a pointer
. The References and Lifetimes Guide is a comprehensive and well-written resource on the subject.
The content of my answer is still relevant if you take into account these two points.
In Rust, there are 3 way of allocating memory :
- On the stack (
T
). This is the same as in C.
- On the task's heap (
@T
). This memory is garbage collected, as in any GC'ed language.
- On the exchange heap (
~T
). The lifetime of this memory depends on who owns it.
Then, depending on the kind of allocation, you can hold a reference to a value using either a @
pointer (only for @
-allocated values), a ~
pointer (only for ~
-allocated values), a &
pointer (borrowed pointer) or a *
pointer (unsafe pointer).
let x: @int = @2;
In this example, the first @
denotes the pointer type, whereas the second one indicates the allocation type. This is an @
-pointer to a GC'd value.
let y: &int = @2;
This is a &
-pointer to a GC'ed value.
&
-pointers are useful, because they can reference any type of memory. When you write a function, you certainly want to declare the parameters as &
-pointer, because the caller can then call the function with values allocated the way he wants. If your function declares a parameter as an @
-pointer, then the caller has no choice but to pass it a heap allocated value.
&
-pointers introduce the notion of lifetime. This is a notion used by the compiler to guarantee that these pointers will never outlive the allocated memory (thus making it "safe" pointers).
The "lifetime" of an @
-allocated value is not known by the compiler : it is not determined statically by the compiler, but dynamically by the runtime.