Skip to content

Commit

Permalink
Update control_flow.rs
Browse files Browse the repository at this point in the history
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
  • Loading branch information
yanok committed Oct 23, 2021
1 parent 3d71e74 commit 508fada
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions library/core/src/ops/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down

0 comments on commit 508fada

Please sign in to comment.