1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-20 01:13:14 +02:00

Use cmp + match in binary tree example (#1587)

Currently, the implementation uses if-then-else chains and `<` and `>`.
This is not the most idiomatic Rust. Instead, we can use `cmp` and
`match` to make the code easier to read.

---------

Co-authored-by: Dustin J. Mitchell <djmitche@google.com>
This commit is contained in:
Martin Huschenbett 2023-12-13 19:39:23 +01:00 committed by GitHub
parent f37aeac3ca
commit ee826ef742
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -13,6 +13,8 @@
// limitations under the License. // limitations under the License.
// ANCHOR: solution // ANCHOR: solution
use std::cmp::Ordering;
// ANCHOR: types // ANCHOR: types
#[derive(Debug)] #[derive(Debug)]
struct BinaryTreeNode<T: Ord + Copy> { struct BinaryTreeNode<T: Ord + Copy> {
@ -42,28 +44,22 @@ impl<T: Ord + Copy> BinaryTree<T> {
right: BinaryTree::new(), right: BinaryTree::new(),
})); }));
} }
Some(n) => { Some(n) => match value.cmp(&n.value) {
if value < n.value { Ordering::Less => n.left.insert(value),
n.left.insert(value); Ordering::Equal => {}
} else if value > n.value { Ordering::Greater => n.right.insert(value),
n.right.insert(value); },
}
}
} }
} }
fn has(&self, value: T) -> bool { fn has(&self, value: T) -> bool {
match &self.0 { match &self.0 {
None => false, None => false,
Some(n) => { Some(n) => match value.cmp(&n.value) {
if value == n.value { Ordering::Less => n.left.has(value),
true Ordering::Equal => true,
} else if value < n.value { Ordering::Greater => n.right.has(value),
n.left.has(value) },
} else {
n.right.has(value)
}
}
} }
} }