Functions in Cairo 1.0#
This article uses Cairo compiler version 2.0.0-rc0. Since Cairo is being updated rapidly, there may be slight differences in syntax between different versions. The content of this article will be updated to the stable version in the future.
Basic Usage#
Functions are essential building blocks in any programming language. A function generally consists of a function name, parameters, and a return value. In Cairo, it is customary to use "snake_case" for function and variable names, like my_function_name
.
use debug::PrintTrait;
fn another_function() {
'Another function.'.print();
}
fn main() {
'Hello, world!'.print();
another_function();
}
The way to call a function is similar to most languages. another_function()
is the syntax for calling a regular function, and 'Hello, world!'.print()
is the syntax for calling a function in a trait.
Parameters & Return Values#
Cairo is a statically-typed language, so the type of each parameter and return value of a function needs to be explicitly specified. If not specified, an error will occur, like this:
fn add(a: felt252, b) {
let c = a + b;
return c;
}
fn main() -> felt252 {
add(3, 5)
}
There are two errors in the above code:
- The type of parameter
b
is not specified. - The function
add
does not specify a return value type, but uses a return statement to return the variablec
.
Correct code:
fn add(a: felt252, b: felt252) -> felt252{
let c = a + b;
return c;
}
fn main() -> felt252 {
add(3, 5)
}
Return Statements#
You can use the return
keyword to explicitly return a value, or you can use a statement without a semicolon to return a value. For example:
fn add(a: felt252, b: felt252) -> felt252 {
// Return a + b
a + b
}
fn sub(a: felt252, b: felt252) -> felt252 {
return a - b;
}
fn main() -> felt252 {
add(3, 5);
sub(11, 7)
}