Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active January 10, 2024 06:53
Show Gist options
  • Save max-itzpapalotl/21fec74a7b9fd7385e43da2469a2dd1a to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/21fec74a7b9fd7385e43da2469a2dd1a to your computer and use it in GitHub Desktop.
10. Control Structures

10. Control Structures

if statements and expressions

fn main() {
    let args : Vec<String> = std::env::args().collect();
    if args.len() > 1 {
        println!("First argument: {}", args[1]);
    } else {
        println!("There is no argument!");
    }
}
fn main() {
    let args : Vec<String> = std::env::args().collect();
    let s = if args.len() > 1 {
        args[1].clone()
    } else {
        "no argument".to_string()
    };
    println!("First argument: {}", s);
}

if let statements

fn main() {
    let args : Vec<String> = std::env::args().collect();
    for a in &args[1..] {
        let x = i64::from_str_radix(a, 10);
        if let Ok(y) = x {
            println!("Found number {}", y);
        } else {
            println!("No number: {}", a);
        }
    }
}

Loops

fn main() {
    let mut i = 0;
    'out: loop {
        let mut j = 0;
        loop {
            if (i * 3 + j * 5) % 15 == 4 {
                println!("4 = {} * 3 + {} * 5 mod 15", i, j);
                break 'out;
            }
            j += 1;
            if j == 3 {
                break;
            }
        }
        i += 1;
    }
}

while loops

fn main() {
    let mut i = 0;
    'out: while i < 5 {
        let mut j = 0;
        while j < 3 {
            if (i * 3 + j * 5) % 15 == 4 {
                println!("4 = {} * 3 + {} * 5 mod 15", i, j);
                break 'out;
            }
            j += 1;
        }
        i += 1;
    }
}

for loops

fn main() {
    'out: for i in 0..5 {
        for j in 0..=2 {
            if (i * 3 + j * 5) % 15 == 4 {
                println!("4 = {} * 3 + {} * 5 mod 15", i, j);
                break 'out;
            }
        }
    }
}
fn main() {
    let args : Vec<String> = std::env::args().collect();
    'out: for a in &args {
        println!("New argument.");
        for c in a.chars() {
            println!("Char: {}", c);
            if c == 'x' {
                break 'out;
            } else if c == 'y' {
                continue 'out;
            }
        }
    }
}

match for scalars

fn main() {
    let args : Vec<String> = std::env::args().collect();
    for a in &args[1..] {
        match i64::from_str_radix(a, 10).unwrap() {
            1 => {
                println!("A 1");
            },
            2 | 3 => {
                println!("Either 2 or 3");
            },
            _ => {
                println!("Something else: {}", a);
            },
        }
    }
}

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment