Rust Triangle Classifier function
Rust Pattern Maching: Exercise-14 with Solution
Write a Rust function that takes a tuple (i32, i32, i32) and returns "Equilateral" if all sides are equal, "Isosceles" if two sides are equal, and "Scalene" otherwise.
Sample Solution:
Rust Code:
// Function to determine the type of triangle based on the lengths of its sides.
fn classify_triangle(sides: (i32, i32, i32)) -> &'static str {
// Extract individual sides from the tuple
let (a, b, c) = sides;
// Check if all sides are equal
if a == b && b == c {
// If all sides are equal, return "Equilateral"
"Equilateral"
// Check if at least two sides are equal
} else if a == b || b == c || c == a {
// If two sides are equal, return "Isosceles"
"Isosceles"
// If no sides are equal, return "Scalene"
} else {
"Scalene"
}
}
fn main() {
// Example usage
let triangle1 = (4, 4, 4); // Equilateral triangle
let triangle2 = (3, 4, 3); // Isosceles triangle
let triangle3 = (3, 4, 5); // Scalene triangle
println!("{:?}: {}", triangle1, classify_triangle(triangle1)); // Output: (3, 3, 3): Equilateral
println!("{:?}: {}", triangle2, classify_triangle(triangle2)); // Output: (3, 4, 3): Isosceles
println!("{:?}: {}", triangle3, classify_triangle(triangle3)); // Output: (3, 4, 5): Scalene
}
Output:
(4, 4, 4): Equilateral (3, 4, 3): Isosceles (3, 4, 5): Scalene
Explanation:
In the exercise above,
This Rust code defines a function "classify_triangle()" that takes a tuple (i32, i32, i32) representing the lengths of the sides of a triangle.
- The function checks if all sides are equal. If so, it returns "Equilateral".
- If not all sides are equal but at least two sides are equal, it returns "Isosceles".
- If no sides are equal, it returns "Scalene".
In the "main()" function, three examples of triangles are provided with their side lengths. The "classify_triangle()" function is called for each triangle, and the result is printed to the console.
Rust Code Editor:
Previous: Rust Function: Analyzing integer slice.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics