We are learning Cairo
, and writing WTF Cairo Tutorials
for Starknet newbies. The tutorials are based on Cairo 2.2.0
.
Twitter: @0xAA_Science|@WTFAcademy_
WTF Academy Community:Discord|Wechat|Website
All codes and tutorials are open-sourced on GitHub: github.com/WTFAcademy/WTF-Cairo
In this chapter, we introduce variable mutability in Cairo, including shadowing and the let
, mut
, and const
keywords.
For safety reasons, variables in Cairo are immutable by default, similar to Rust. Once a variable is assigned a value, it cannot be changed afterwards.
// In Cairo, variables are immutable by default
let x_immutable = 5;
// The following code will result in an error
// x_immutable = 10
Mutability can be very useful and can make code more convenient to write. Like in Rust, you can use the mut
keyword to declare mutable variables:
// Use the `mut` keyword to declare mutable variables
let mut x_mutable = 5;
x_mutable = 10;
Similar to immutable variables, constants are values bound to a name and are not allowed to change. However, there are a few differences between constants and variables:
- Constants are declared with the
const
keyword, notlet
. - The type of the value must be annotated.
- Constants can only be declared and assigned in the global scope (within a contract and outside of functions).
- You can't use
mut
withconst
.
const CONST_NUMBER: felt252 = 888;
#[external(v0)]
fn mutable_and_const(self: @ContractState) {
// You can assign a const to a variable
let y_immutable = CONST_NUMBER + 2;
}
In Cairo, you can declare a new variable with the same name as a previous variable, effectively shadowing
the previous one. This is different from using mut
, as you are creating a new variable when you use the let
keyword again. This allows you to change the type or mutability of the value while reusing the same name.
#[external(v0)]
fn shadow(self: @ContractState) -> felt252 {
// Shadowing: you can declare a new variable with the same name as previous ones.
let x_shadow = 5;
// You can change the data type or mutability with shadowing
let x_shadow = 10_u8;
let mut x_shadow = 15;
return x_shadow;
}
In this chapter, we delved into variable mutability in Cairo, including shadowing and the let
, mut
, and const
keywords.