You've already forked comprehensive-rust
							
							
				mirror of
				https://github.com/google/comprehensive-rust.git
				synced 2025-10-31 08:37:45 +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:
		
				
					committed by
					
						 GitHub
						GitHub
					
				
			
			
				
	
			
			
			
						parent
						
							f37aeac3ca
						
					
				
				
					commit
					ee826ef742
				
			| @@ -13,6 +13,8 @@ | ||||
| // limitations under the License. | ||||
|  | ||||
| // ANCHOR: solution | ||||
| use std::cmp::Ordering; | ||||
|  | ||||
| // ANCHOR: types | ||||
| #[derive(Debug)] | ||||
| struct BinaryTreeNode<T: Ord + Copy> { | ||||
| @@ -42,28 +44,22 @@ impl<T: Ord + Copy> BinaryTree<T> { | ||||
|                     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), | ||||
|             }, | ||||
|         } | ||||
|     } | ||||
|  | ||||
|   | ||||
		Reference in New Issue
	
	Block a user