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!
- 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
- Run the example:
- Copy the example into a ownership.cairo file and run with:
%!s(<nil>) ownership.cairo