Functions in Cairo 1.0#
The version of the Cairo compiler used in this article is 2.0.0-rc0. Since Cairo is being updated rapidly, there may be slight differences in syntax between different versions, and the article content 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" naming convention 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 functions are called 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. Not specifying the type will result in an error, like:
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 parameter
b
is not specified with a type. - The function
add
does not specify a return value type, but uses a return statement to return the variablec
.
Corrected 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 {
// Returns a + b
a + b
}
fn sub(a: felt252, b: felt252) -> felt252 {
return a - b;
}
fn main() -> felt252 {
add(3, 5);
sub(11, 7)
}