控制流

根据条件是否为真来决定是否执行某些代码,以及根据条件是否为真来重复运行一段 代码的能力是大部分编程语言的基本组成部分。Cairo 代码中最常见的用来控制执行 流的结构是 if 表达式和循环。

if Expressions

if 表达式允许根据条件执行不同的代码分支。你提供一个条件并表示 “如果条件满 足,运行这段代码;如果条件不满足,不运行这段代码。”

Create a new project called branches in your cairo_projects directory to explore the if expression. In the src/lib.cairo file, input the following:

fn main() {
    let number = 3;

    if number == 5 {
        println!("condition was true and number = {}", number);
    } else {
        println!("condition was false and number = {}", number);
    }
}

所有的 if 表达式都以关键字 if 开始,其后跟一个条件。在这个例子中,条件检查 变量 number 的值是否等于 5。在条件为 true 时希望执行的代码块位于紧跟条件 之后的大括号中。

另外,我们也可以包含一个可选的 else 表达式来提供一个在条件为 false 时应当执行的代码块,这里我们就这么做了。如果不提供 else 表达式并且条件为 false 时,程序会直接忽略 if 代码块并继续执行下面的代码。

尝试运行这段代码;你应该看到以下输出:

$ scarb cairo-run 
   Compiling no_listing_24_if v0.1.0 (listings/ch02-common-programming-concepts/no_listing_27_if/Scarb.toml)
    Finished release target(s) in 1 second
     Running no_listing_24_if
condition was false and number = 3
Run completed successfully, returning []

让我们试着改变 number 的值使条件为 true 时看看会发生什么:

    let number = 5;
$ scarb cairo-run
condition was true and number = 5
Run completed successfully, returning []

It’s also worth noting that the condition in this code must be a bool. If the condition isn’t a bool, we’ll get an error. For example, try running the following code:

fn main() {
    let number = 3;

    if number {
        println!("number was three");
    }
}

The if condition evaluates to a value of 3 this time, and Cairo throws an error:

$ scarb build 
   Compiling no_listing_28_bis_if_not_bool v0.1.0 (listings/ch02-common-programming-concepts/no_listing_28_bis_if_not_bool/Scarb.toml)
error: Mismatched types. The type `core::bool` cannot be created from a numeric literal.
 --> listings/ch02-common-programming-concepts/no_listing_28_bis_if_not_bool/src/lib.cairo:4:18
    let number = 3;
                 ^

error: could not compile `no_listing_28_bis_if_not_bool` due to previous error

The error indicates that Cairo inferred the type of number to be a bool based on its later use as a condition of the if statement. It tries to create a bool from the value 3, but Cairo doesn't support instantiating a bool from a numeric literal anyway - you can only use true or false to create a bool. Unlike languages such as Ruby and JavaScript, Cairo will not automatically try to convert non-Boolean types to a Boolean. If we want the if code block to run only when a number is not equal to 0, for example, we can change the if expression to the following:

fn main() {
    let number = 3;

    if number != 0 {
        println!("number was something other than zero");
    }
}

Running this code will print number was something other than zero.

Handling Multiple Conditions with else if

You can use multiple conditions by combining if and else in an else if expression. For example:

fn main() {
    let number = 3;

    if number == 12 {
        println!("number is 12");
    } else if number == 3 {
        println!("number is 3");
    } else if number - 2 == 1 {
        println!("number minus 2 is 1");
    } else {
        println!("number not found");
    }
}

这个程序有四种可能的路径。运行后,你应该看到以下输出:

$ scarb cairo-run 
   Compiling no_listing_25_else_if v0.1.0 (listings/ch02-common-programming-concepts/no_listing_30_else_if/Scarb.toml)
    Finished release target(s) in 1 second
     Running no_listing_25_else_if
number is 3
Run completed successfully, returning []

When this program executes, it checks each if expression in turn and executes the first body for which the condition evaluates to true. Note that even though number - 2 == 1 is true, we don’t see the output number minus 2 is 1 nor do we see the number not found text from the else block. That’s because Cairo only executes the block for the first true condition, and once it finds one, it doesn’t even check the rest. Using too many else if expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Cairo branching construct called match for these cases.

Using if in a let Statement

Because if is an expression, we can use it on the right side of a let statement to assign the outcome to a variable.

fn main() {
    let condition = true;
    let number = if condition {
        5
    } else {
        6
    };

    if number == 5 {
        println!("condition was true and number is {}", number);
    }
}
$ scarb cairo-run 
   Compiling no_listing_26_if_let v0.1.0 (listings/ch02-common-programming-concepts/no_listing_31_if_let/Scarb.toml)
    Finished release target(s) in 1 second
     Running no_listing_26_if_let
condition was true and number is 5
Run completed successfully, returning []

The number variable will be bound to a value based on the outcome of the if expression, which will be 5 here.

Repetition with Loops

It’s often useful to execute a block of code more than once. For this task, Cairo provides a simple loop syntax, which will run through the code inside the loop body to the end and then start immediately back at the beginning. To experiment with loops, let’s create a new project called loops.

Cairo has three kinds of loops: loop, while, and for. Let’s try each one.

Repeating Code with loop

The loop keyword tells Cairo to execute a block of code over and over again forever or until you explicitly tell it to stop.

As an example, change the src/lib.cairo file in your loops directory to look like this:

fn main() {
    loop {
        println!("again!");
    }
}

When we run this program, we’ll see again! printed over and over continuously until either the program runs out of gas or we stop the program manually. Most terminals support the keyboard shortcut ctrl-c to interrupt a program that is stuck in a continual loop. Give it a try:

$ scarb cairo-run --available-gas=20000000
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished release target(s) in 0 seconds
     Running loops
again!
again!
again!
^Cagain!

The symbol ^C represents where you pressed ctrl-c. You may or may not see the word again! printed after the ^C, depending on where the code was in the loop when it received the interrupt signal.

Note: Cairo prevents us from running program with infinite loops by including a gas meter. The gas meter is a mechanism that limits the amount of computation that can be done in a program. By setting a value to the --available-gas flag, we can set the maximum amount of gas available to the program. Gas is a unit of measurement that expresses the computation cost of an instruction. When the gas meter runs out, the program will stop. In the previous case, we set the gas limit high enough for the program to run for quite some time.

It is particularly important in the context of smart contracts deployed on Starknet, as it prevents from running infinite loops on the network. If you're writing a program that needs to run a loop, you will need to execute it with the --available-gas flag set to a value that is large enough to run the program.

Now, try running the same program again, but this time with the --available-gas flag set to 200000 instead of 2000000000000. You will see the program only prints again! 3 times before it stops, as it ran out of gas to keep executing the loop.

Fortunately, Cairo also provides a way to break out of a loop using code. You can place the break keyword within the loop to tell the program when to stop executing the loop.

fn main() {
    let mut i: usize = 0;
    loop {
        if i > 10 {
            break;
        }
        println!("i = {}", i);
        i += 1;
    }
}

The continue keyword tells the program to go to the next iteration of the loop and to skip the rest of the code in this iteration. Let's add a continue statement to our loop to skip the println! statement when i is equal to 5.

fn main() {
    let mut i: usize = 0;
    loop {
        if i > 10 {
            break;
        }
        if i == 5 {
            i += 1;
            continue;
        }
        println!("i = {}", i);
        i += 1;
    }
}

i等于5时,执行这个程序将不会打印i的值。

Returning Values from Loops

One of the uses of a loop is to retry an operation you know might fail, such as checking whether an operation has succeeded. You might also need to pass the result of that operation out of the loop to the rest of your code. To do this, you can add the value you want returned after the break expression you use to stop the loop; that value will be returned out of the loop so you can use it, as shown here:

fn main() {
    let mut counter = 0;

    let result = loop {
        if counter == 10 {
            break counter * 2;
        }
        counter += 1;
    };

    println!("The result is {}", result);
}

Before the loop, we declare a variable named counter and initialize it to 0. Then we declare a variable named result to hold the value returned from the loop. On every iteration of the loop, we check whether the counter is equal to 10, and then add 1 to the counter variable. When the condition is met, we use the break keyword with the value counter * 2. After the loop, we use a semicolon to end the statement that assigns the value to result. Finally, we print the value in result, which in this case is 20.

Conditional Loops with while

A program will often need to evaluate a condition within a loop. While the condition is true, the loop runs. When the condition ceases to be true, the program calls break, stopping the loop. It’s possible to implement behavior like this using a combination of loop, if, else, and break; you could try that now in a program, if you’d like. However, this pattern is so common that Cairo has a built-in language construct for it, called a while loop.

In Listing 2-2, we use while to loop the program three times, counting down each time after printing the value of number, and then, after the loop, print a message and exit.

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");
        number -= 1;
    };

    println!("LIFTOFF!!!");
}

Listing 2-2: Using a while loop to run code while a condition holds true.

This construct eliminates a lot of nesting that would be necessary if you used loop, if, else, and break, and it’s clearer. While a condition evaluates to true, the code runs; otherwise, it exits the loop.

Looping Through a Collection with for

You can also use the while construct to loop over the elements of a collection, such as an array. For example, the loop in Listing 2-3 prints each element in the array a.

fn main() {
    let a = [10, 20, 30, 40, 50].span();
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);
        index += 1;
    }
}

Listing 2-3: Looping through each element of a collection using a while loop

Here, the code counts up through the elements in the array. It starts at index 0, and then loops until it reaches the final index in the array (that is, when index < 5 is no longer true). Running this code will print every element in the array:

$ scarb cairo-run 
   Compiling no_listing_45_iter_loop_while v0.1.0 (listings/ch02-common-programming-concepts/no_listing_45_iter_loop_while/Scarb.toml)
    Finished release target(s) in 2 seconds
     Running no_listing_45_iter_loop_while
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
Run completed successfully, returning []

All five array values appear in the terminal, as expected. Even though index will reach a value of 5 at some point, the loop stops executing before trying to fetch a sixth value from the array.

However, this approach is error prone; we could cause the program to panic if the index value or test condition is incorrect. For example, if you changed the definition of the a array to have four elements but forgot to update the condition to while index < 4, the code would panic. It’s also slow, because the compiler adds runtime code to perform the conditional check of whether the index is within the bounds of the array on every iteration through the loop.

As a more concise alternative, you can use a for loop and execute some code for each item in a collection. A for loop looks like the code in Listing 2-4.

fn main() {
    let a = [10, 20, 30, 40, 50].span();

    for element in a {
        println!("the value is: {element}");
    }
}

Listing 2-4: Looping through each element of a collection using a for loop

When we run this code, we’ll see the same output as in Listing 2-3. More importantly, we’ve now increased the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array or not going far enough and missing some items.

Using the for loop, you wouldn’t need to remember to change any other code if you changed the number of values in the array, as you would with the method used in Listing 2-3.

The safety and conciseness of for loops make them the most commonly used loop construct in Cairo. Even in situations in which you want to run some code a certain number of times, as in the countdown example that used a while loop in Listing 2-2. Another way to run code a certain number of times would be to use a Range, provided by the core library, which generates all numbers in sequence starting from one number and ending before another number.

Here’s how you can use a Range to count from 1 to 3:

fn main() {
    for number in 1..4_u8 {
        println!("{number}!");
    };
    println!("Go!!!");
}

This code is a bit nicer, isn’t it?

Equivalence Between Loops and Recursive Functions

Loops and recursive functions are two common ways to repeat a block of code multiple times. The loop keyword is used to create an infinite loop that can be broken by using the break keyword.

fn main() -> felt252 {
    let mut x: felt252 = 0;
    loop {
        if x == 2 {
            break;
        } else {
            x += 1;
        }
    };
    x
}

Loops can be transformed into recursive functions by calling the function within itself. Here is an example of a recursive function that mimics the behavior of the loop example above.

fn main() -> felt252 {
    recursive_function(0)
}

fn recursive_function(mut x: felt252) -> felt252 {
    if x == 2 {
        x
    } else {
        recursive_function(x + 1)
    }
}

In both cases, the code block will run indefinitely until the condition x == 2 is met, at which point the value of x will be displayed.

In Cairo, loops and recursions are not only conceptually equivalent: they are also compiled down to similar low-level representations. To understand this, we can compile both examples to Sierra, and analyze the Sierra Code generated by the Cairo compiler for both examples. Add the following in your Scarb.toml file:

[lib]
sierra-text = true

Then, run scarb build to compile both examples. You will find the Sierra code generated by for both examples is extremely similar, as the loop is compiled to a recursive function in the Sierra statements.

Note: For our example, our findings came from understanding the statements section in Sierra that shows the execution traces of the two programs. If you are curious to learn more about Sierra, check out Exploring Sierra.

Summary

You made it! This was a sizable chapter: you learned about variables, data types, functions, comments, if expressions and loops! To practice with the concepts discussed in this chapter, try building programs to do the following:

  • Generate the n-th Fibonacci number.
  • Compute the factorial of a number n.

现在,我们将在下一章回顾 Cairo 中常见的集合类型。