Rust - Match control flow statements

taeyang koh·2024년 11월 11일

This is code snippet about match control which demonstrates how each greeting gets answer.

use std::io;

fn main() {
    println!("Please enter a greeting:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed to read input");

    // to allow for case-insensitive matching, we convert the input to lowercase
    let name = name.to_lowercase();
    
    // use of match expression to pattern match against variable "name"
    match name.trim() {
        "good bye" => println!("Sorry to see you go."),
        "hello" => println!("Hi, nice to meet you!"),
        "morning" => println!("Good morning!"),
        "how are you?" => println!("I'm doing well, thank you!"),
        _ => println!("I can't find a greeting, good bye."),
    }
}

key terms:
shadowing: A variable redeclaration with the same name but different value and/or scope within in the same context

profile
Passionate about crafting optimized systems that contribute to a brighter, better future

0개의 댓글