StarknetAstro

StarknetAstro

01_Variables in Cairo

01_Variables in Cairo#

The version of the Cairo compiler used in this article is 2.0.0-rc0. Since Cairo is being updated rapidly, the syntax may vary slightly in different versions, and the content of the article will be updated to the stable version in the future.

Variables are the most basic elements in programming languages.

Basic Usage#

Creating a variable

use debug::PrintTrait;

fn main() {
    let x = 5;
    let y:u8 = 6;
    x.print();
}

Use the let keyword to create a variable. PrintTrait is a printing utility library provided by the official library.

Variable Mutability#

Cairo uses an immutable memory model, which means that once a memory space is assigned a value, it cannot be overwritten and can only be read.

This means that all variables in Cairo are immutable by default (which may sound counterintuitive 🙃️).

Try running the following code (using the command: cairo-run --path $FILE_CAIRO)

use debug::PrintTrait;
fn main() {
    let x = 5;
    x.print();
    x = 6;
    x.print();
}

You will get the following error:

error: Cannot assign to an immutable variable.
 --> c01_var.cairo:5:5
    x = 6;
    ^***^

Error: failed to compile: src/c01_var.cairo

To make a variable mutable, you need to use the mut keyword:

use debug::PrintTrait;
fn main() {
    let mut x = 5;
    x.print();
    x = 6;
    x.print();
}

In the above example, the x variable is preceded by the mut keyword, so it can run normally.

Immutable variables are somewhat similar to constants. Can they be used as constants?

Shadowing#

Shadowing in Cairo is similar to Rust, which means that different variables can use the same variable name. Let's take a look at a specific example:

use debug::PrintTrait;
fn main() {
    let mut x = 5_u32;
    let x: felt252 = 10;
    {
	    // Only affects variables within the braces, not outside the braces
        let x = x * 2;
        'Inner scope x value is:'.print();
        x.print()
    }
    'Outer scope x value is:'.print();
    x.print();
}

In the above example, the variable x defined in let x: felt252 = 10; completely shadows the previous x variable, which is why it is called shadowing. It has the following characteristics:

  1. Redefined using the let keyword;
  2. The redefined variable can have a different data type unrelated to the previous type;
  3. Shadowing only affects variables in the same namespace;
  4. Whether the variable is immutable or mutable, it can be shadowed.

Note: When using shadowing, try to avoid using the same variable name in different namespaces, as it can make it difficult to locate bugs.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.