Skip to content
This repository has been archived by the owner on Sep 25, 2024. It is now read-only.

Latest commit

 

History

History
31 lines (26 loc) · 2.02 KB

12. Options.md

File metadata and controls

31 lines (26 loc) · 2.02 KB

Option

Writing Provable programs necessitates that our programs are able to run as intended. Usually, when a Cairo program encounters an error, it throws a panic. However, it is sometimes desireable to catch failures of parts of our programs instead of calling panic.

In cairo 1.0, there is the Option type which represents values that may or may not be present. The Option type is similar to that of Rust, as Cairo 1.0 is heavily borrowed from Rust. In cairo 1.0, the Option type just as is in Rust can be either Some or None. What this means is if a value is present it is wrapped in a variant Some and when absent it is wrapped in the variant None

Cairo 1.0 provides two methods is_some and is_none which is is used to check whether an Option contains a value or not. The is_some method returns true if an Option contains a value and false if it doesn't. Similarly, the is_none method returns true if the Option does not contain a value and false if it does contain a value.

For proper understanding, let's consider the following example in Cairo 1.0:

use option::OptionTrait;
use debug::PrintTrait;

fn main() {
    let some_value: Option<u8> = Some(1_u8);
    let none_value: Option<u8> = None(());
    if some_value.is_some() {
        ('The value is present').print();
    } else {
    ('The value is not present').print();
    }
    if none_value.is_none() {
    ('The value is not present').print();
    } else {
        ('The value is present').print();
    }
}

In the above example, our function main first creates two Option values, one with value called some_value and the other with no value called none_value Then in the conditional statement, we use the is_some method to check if the value is present and is_none if the value is not present. In both conditions we print out a corresponding message.

From this, we clearly see how in Cairo 1.0 Option, is_some and is_none provides the ability of writing reliable and robust programs through dealing with absent values.