nandi/rustnimpublic Fork 0
d4592812fae6b652d94be442f5b3a408d3ab21b6
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Add enums, Option/Result, `?`, and the machinery base16ct needs around them b0ccd80 · on d4592812fae6b652d94be442f5b3a408d3ab21b6 · nandithebull · 11h ago
021-option.rs · 25 lines · 638 BRust Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Option, and the type alias expansion that `Result<T>` in base16ct needs.
type MyResult<T> = Result<T, i32>;

fn first_even(a: i32, b: i32) -> Option<i32> {
    if a % 2 == 0 {
        Some(a)
    } else if b % 2 == 0 {
        Some(b)
    } else {
        None
    }
}

fn checked(n: i32) -> MyResult<i32> {
    let v: Option<i32> = first_even(n, n + 1);
    let got: i32 = v.ok_or(-1)?;
    Ok(got * 10)
}

fn main() {
    println!("{:?} {:?}", first_even(2, 3), first_even(1, 3));
    println!("{}", first_even(1, 4).unwrap());
    println!("{}", first_even(1, 3).unwrap_or(-7));
    println!("{:?} {:?}", checked(2), checked(1));
}