w3resource

Rust Function: Check vowel or consonant

Rust Pattern Maching: Exercise-2 with Solution

Write a Rust function that takes a tuple (char, i32) and returns "Vowel" if the first element is a vowel ('a', 'e', 'i', 'o', 'u') and "Consonant" otherwise.

Sample Solution:

Rust Code:

// Define a function named 'check_char_type' that takes a tuple '(ch, num)' as input and returns a static string slice.
fn check_char_type(tuple: (char, i32)) -> &'static str {
    // Destructure the tuple into its elements.
    let (ch, _) = tuple;
    // Check if the character 'ch' is a vowel ('a', 'e', 'i', 'o', 'u').
    if ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' {
        // If `ch` is a vowel, return "Vowel".
        "Vowel"
    } else {
        // If 'ch' is not a vowel, return "Consonant".
        "Consonant"
    }
}

fn main() {
    // Define a tuple containing a character and an integer.
    let my_tuple: (char, i32) = ('e', 10);
    // Print the result of calling 'check_char_type' function with 'my_tuple' as input.
    println!("{}", check_char_type(my_tuple)); // Output: Vowel
}

Output:

Vowel

Explanation:

In the exercise above,

  • Define a function "check_char_type()" that takes a tuple (char, i32) as input and returns a static string slice (&'static str).
  • Inside the function, we destructure the input tuple into its two elements using pattern matching. We only need the first element 'ch', so we use _ to ignore the second element.
  • We then check if the character 'ch' is a vowel ('a', 'e', 'i', 'o', 'u'). If it matches any of these vowels, we return the string "Vowel".
  • If the character is not a vowel, we return the string "Consonant".
  • In the "main()" function, we define a tuple 'my_tuple' containing a character 'a' and an integer 10.
  • We call the "check_char_type()" function with 'my_tuple' as input and print the result. In this case, the output will be "Vowel", indicating that the character 'a' is indeed a vowel.

Rust Code Editor:


Previous: Rust Function: Check even or odd.
Next: Rust Function: Check Result Success or Error.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-2.php