Rust heap references

When a variable pointing to a value on the heap—like an array—is assigned to another variable, the old variable is invalidated. The value is said to have moved to the new variable. This is done to allow the memory management system of Rust to free memory on the heap at a distinct moment in time: whenever the one valid variable goes out of scope.

The same movement of values happens when calling a function in Rust. If a heap variable is used as an argument, the function called takes ownership of that variable, which is not automatically returned at the end of the function call. Heap variables passed to functions will normally be invalidated by the process, as their scope ended at the end of the function call.

Returning a variable has the same effect. A returned variable will not be considered to have gone out of scope, and the function caller would be able to access the returned value. This can be used to return ownership back to the function caller. The called function could return its intended return value, along with every heap argument packaged into a big tuple. This is very tedious, however, and is not conventionally necessary.

Rust has another feature called references. Unlike ownership, which is passed between functions, references are borrowed access to a variable. Once the reference goes out of scope, the original owners access is restored automatically. References come in two forms, mutable and immutable. In order to avoid cross-cutting side effects from mutations, a single variable may only have one mutable reference at a time. This is similar to the approach described in the Clojure documentation on transients. A single function can alter a value, safe in the assurance that they are not affection other code, or many functions can read a value, safe in the assurance that none of the other functions may affect their code.

#software