w3resource

Rust Function: Compare Tuple elements

Rust Pattern Maching: Exercise-6 with Solution

Write a Rust function that takes a tuple (i32, i32) and returns "Equal" if both elements are equal, "Increasing" if the first element is less than the second, and "Decreasing" if the first element is greater than the second.

Sample Solution:

Rust Code:

// Function that checks the relationship between two elements of a tuple.
fn check_tuple(tuple: (i32, i32)) -> &'static str {
    match tuple {
        (x, y) if x == y => "Equal",
        (x, y) if x < y => "Increasing",
        _ => "Decreasing",
    }
}

fn main() {
    // Example usage
    let tuple1 = (2, 2);
    let tuple2 = (4, 7);
    let tuple3 = (12, 10);

    println!("{:?}: {}", tuple1, check_tuple(tuple1)); // Output: (5, 5): Equal
    println!("{:?}: {}", tuple2, check_tuple(tuple2)); // Output: (3, 8): Increasing
    println!("{:?}: {}", tuple3, check_tuple(tuple3)); // Output: (10, 3): Decreasing
}

Output:

(2, 2): Equal
(4, 7): Increasing
(12, 10): Decreasing

Explanation:

The above Rust code defines a function "check_tuple()" that takes a tuple of two integers and returns a string indicating the relationship between the elements of the tuple.

  • If both elements of the tuple are equal (x == y), it returns "Equal".
  • If the first element is less than the second (x < y), it returns "Increasing".
  • Otherwise, it returns "Decreasing".

In the "main()" function, three tuples are defined (tuple1, tuple2, and tuple3). The "check_tuple()" function is called with each tuple as an argument, and the result is printed along with the tuple itself.

Rust Code Editor:


Previous: Rust Function: Check vector empty or not.
Next: Rust Function: Check order of integers.

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-6.php