Rust Program to Implement switch statement on strings


Implement switch statement on strings

Rust Programming Language


Implement switch statement on strings


Problem


In Rust, there is no built-in switch statement for strings, but we can implement a similar functionality using the match expression. Here's an example program that uses a match expression to perform different actions based on the input string.

Input


use std::io;

fn main() {
    println!("Enter a command:");
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();

    match input.trim() {
        "start" => println!("Starting the application..."),
        "stop" => println!("Stopping the application..."),
        "pause" => println!("Pausing the application..."),
        "resume" => println!("Resuming the application..."),
        _ => println!("Unknown command!"),
    }
}{codeBox}


Output


Here's an example output for an input of 'start':

Enter a command:
start
Starting the application...{codeBox}

And here's an example output for an input of 'unknown':

Enter a command:
unknown
Unknown command!{codeBox}


Explanation


In this program, we use the io module to get user input for a command. We then use a match expression to match the input string against different patterns. If the input string matches one of the patterns, we perform the corresponding action, otherwise we print an error message.

The underscore (_) pattern in the last arm of the match expression is a catch-all pattern that matches any value that didn't match any of the previous patterns.


Post a Comment