From ee826ef742fa0a8e622ad42a7196aa7ccd5d85ef Mon Sep 17 00:00:00 2001 From: Martin Huschenbett Date: Wed, 13 Dec 2023 19:39:23 +0100 Subject: [PATCH] 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 --- src/smart-pointers/exercise.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/smart-pointers/exercise.rs b/src/smart-pointers/exercise.rs index c4134c2f..dc9e8cd3 100644 --- a/src/smart-pointers/exercise.rs +++ b/src/smart-pointers/exercise.rs @@ -13,6 +13,8 @@ // limitations under the License. // ANCHOR: solution +use std::cmp::Ordering; + // ANCHOR: types #[derive(Debug)] struct BinaryTreeNode { @@ -42,28 +44,22 @@ impl BinaryTree { right: BinaryTree::new(), })); } - Some(n) => { - if value < n.value { - n.left.insert(value); - } else if value > n.value { - n.right.insert(value); - } - } + Some(n) => match value.cmp(&n.value) { + Ordering::Less => n.left.insert(value), + Ordering::Equal => {} + Ordering::Greater => n.right.insert(value), + }, } } fn has(&self, value: T) -> bool { match &self.0 { None => false, - Some(n) => { - if value == n.value { - true - } else if value < n.value { - n.left.has(value) - } else { - n.right.has(value) - } - } + Some(n) => match value.cmp(&n.value) { + Ordering::Less => n.left.has(value), + Ordering::Equal => true, + Ordering::Greater => n.right.has(value), + }, } }