cairo by example

ownership

All Cairo code has to abide by two ownership rules: - each value in Cairo has one and only one owner at a time, - when the owner goes out of scope, the value will be dropped

use array::ArrayTrait;

fn foo(arr: Array<u128>) {
    // foo takes ownership of the array.
    // when this function returns, arr is dropped.
}

fn main() {
    // as the creator of arr, the main function owns the array
    let arr = ArrayTrait::<u128>::new();

    foo(arr); // moves ownership of the array to function call

    // foo(arr); <- fails to compile, as main doesn't own the array anymore
}


Try it out!
  1. Install the toolchain:
    • For macOS and Linux, run our script:
    • curl -sL https://raw.githubusercontent.com/lambdaclass/cairo-by-example/main/build/installer.sh | bash -s 2.2.0
    • For Windows and others, please see the official guide
  2. Run the example:
    1. Copy the example into a ownership.cairo file and run with:
    2. %!s(<nil>) ownership.cairo

prev (pattern matching) next (clone and copy)