cairo by example

named parameters

Named parameters allow you to specify the names of arguments when you call a function. If you want to use named parameters, you need to specify the name of the parameter and the value you want to pass it. Note that they still need to be in the same order as declared in the function.

fn foo(x: u8, y: u8) {
    // ...
}

fn main() {
    let first_arg = 3;
    let second_arg = 4;
    // parameter_name: value
    foo(x: first_arg, y: second_arg);
    // foo(y: second_arg, x: first_arg); <- this would produce an error
}

If you pass a variable with the same name as the parameter, you can use a shorter syntax:

fn foo(x: u8, y: u8) {
    // ...
}

fn main() {
    let x = 1;
    let y = 2;
    foo(:x, :y);
}


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 named_parameters.cairo file and run with:
    2. %!s(<nil>) named_parameters.cairo

prev (functions) next (if expression)