Skip to content

Commit b1ae1ba

Browse files
committed
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 rust-lang#90063
1 parent 2859246 commit b1ae1ba

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

core/src/ops/control_flow.rs

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,40 @@ use crate::{convert, ops};
3434
/// }
3535
///
3636
/// impl<T> TreeNode<T> {
37-
/// pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
37+
/// pub fn traverse_inorder<B>(&self, f: &impl Fn(&T) -> ControlFlow<B>) -> ControlFlow<B> {
3838
/// if let Some(left) = &self.left {
39-
/// left.traverse_inorder(&mut f)?;
39+
/// left.traverse_inorder(f)?;
4040
/// }
4141
/// f(&self.value)?;
4242
/// if let Some(right) = &self.right {
43-
/// right.traverse_inorder(&mut f)?;
43+
/// right.traverse_inorder(f)?;
4444
/// }
4545
/// ControlFlow::Continue(())
4646
/// }
4747
/// }
48+
///
49+
/// let node = TreeNode {
50+
/// value: 0,
51+
/// left: Some(Box::new(TreeNode {
52+
/// value: 1,
53+
/// left: None,
54+
/// right: None
55+
/// })),
56+
/// right: Some(Box::new(TreeNode {
57+
/// value: 2,
58+
/// left: None,
59+
/// right: None
60+
/// }))
61+
/// };
62+
///
63+
/// node.traverse_inorder(& |val| {
64+
/// println!("{}", val);
65+
/// if *val <= 0 {
66+
/// ControlFlow::Break(())
67+
/// } else {
68+
/// ControlFlow::Continue(())
69+
/// }
70+
/// });
4871
/// ```
4972
#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
5073
#[derive(Debug, Clone, Copy, PartialEq)]

0 commit comments

Comments
 (0)