language-design
Ownership

What Is Ownership?

Rust

Rust’s central feature is ownership. Although the feature is straightforward to explain, it has deep implications for the rest of the language.

All programs have to manage the way they use a computer’s memory while running.

  • Some languages have garbage collection that constantly looks for no longer used memory as the program runs;
  • in other languages, the programmer must explicitly allocate and free the memory.

Rust uses a third approach:

memory is managed through a system of ownership with a set of rules that the compiler checks at compile time.

No run-time costs are incurred for any of the ownership features.

Cairo

In Cairo, ownership applies to variables and not to values.

A value can safely be referred to by many different variables (even if they are mutable variables), as the value itself is always immutable.

Variables however can be mutable, so the compiler must ensure that constant variables aren't accidentally modified by the programmer. This makes it possible to talk about ownership of a variable: the owner is the code that can read (and write if mutable) the variable.

This means that variables (not values) follow similar rules to Rust values:

  • Each variable in Cairo has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the variable is destroyed.