about summary refs log tree commit diff
diff options
context:
space:
mode:
authorIlya Yanok <ilya.yanok@gmail.com>2021-10-23 11:40:46 +0200
committerIlya Yanok <ilya.yanok@gmail.com>2021-10-23 11:40:46 +0200
commit508fadab16ec36c57daa8f0361db60848d31c0f7 (patch)
tree89ccab1c65f13b87fe729e490d723e7300ad087d
parent3d71e749a244890cd370d49963e747cf92f4a037 (diff)
downloadrust-508fadab16ec36c57daa8f0361db60848d31c0f7.tar.gz
rust-508fadab16ec36c57daa8f0361db60848d31c0f7.zip
Update control_flow.rs
Fix and extent ControlFlow `traverse_inorder` example

1. The existing example compiles on its own, but any usage fails to be monomorphised and so doesn't compile. Fix that by using Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.

Fixes #90063
-rw-r--r--library/core/src/ops/control_flow.rs29
1 files changed, 26 insertions, 3 deletions
diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs
index cd2d57699c9..ec00d0fe05b 100644
--- a/library/core/src/ops/control_flow.rs
+++ b/library/core/src/ops/control_flow.rs
@@ -34,17 +34,40 @@ use crate::{convert, ops};
 /// }
 ///
 /// impl<T> TreeNode<T> {
-///     pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
+///     pub fn traverse_inorder<B>(&self, f: &impl Fn(&T) -> ControlFlow<B>) -> ControlFlow<B> {
 ///         if let Some(left) = &self.left {
-///             left.traverse_inorder(&mut f)?;
+///             left.traverse_inorder(f)?;
 ///         }
 ///         f(&self.value)?;
 ///         if let Some(right) = &self.right {
-///             right.traverse_inorder(&mut f)?;
+///             right.traverse_inorder(f)?;
 ///         }
 ///         ControlFlow::Continue(())
 ///     }
 /// }
+///
+/// let node = TreeNode {
+///     value: 0,
+///     left: Some(Box::new(TreeNode {
+///         value: 1,
+///         left: None,
+///         right: None
+///     })),
+///     right: Some(Box::new(TreeNode {
+///         value: 2,
+///         left: None,
+///         right: None
+///     }))
+/// };
+///
+/// node.traverse_inorder(& |val| {
+///     println!("{}", val);
+///     if *val <= 0 {
+///         ControlFlow::Break(())
+///     } else {
+///         ControlFlow::Continue(())
+///     }
+/// });
 /// ```
 #[stable(feature = "control_flow_enum_type", since = "1.55.0")]
 #[derive(Debug, Clone, Copy, PartialEq)]