Skip to content

Commit 7d4f234

Browse files
authored
Rollup merge of rust-lang#90196 - yanok:master, r=scottmcm
Fix and extent ControlFlow `traverse_inorder` example 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
2 parents 787556a + 4e8e99e commit 7d4f234

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

core/src/ops/control_flow.rs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use crate::{convert, ops};
2424
/// ```
2525
///
2626
/// A basic tree traversal:
27-
/// ```no_run
27+
/// ```
2828
/// use std::ops::ControlFlow;
2929
///
3030
/// pub struct TreeNode<T> {
@@ -34,17 +34,42 @@ 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: &mut impl FnMut(&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
/// }
47+
/// fn leaf(value: T) -> Option<Box<TreeNode<T>>> {
48+
/// Some(Box::new(Self { value, left: None, right: None }))
49+
/// }
4750
/// }
51+
///
52+
/// let node = TreeNode {
53+
/// value: 0,
54+
/// left: TreeNode::leaf(1),
55+
/// right: Some(Box::new(TreeNode {
56+
/// value: -1,
57+
/// left: TreeNode::leaf(5),
58+
/// right: TreeNode::leaf(2),
59+
/// }))
60+
/// };
61+
/// let mut sum = 0;
62+
///
63+
/// let res = node.traverse_inorder(&mut |val| {
64+
/// if *val < 0 {
65+
/// ControlFlow::Break(*val)
66+
/// } else {
67+
/// sum += *val;
68+
/// ControlFlow::Continue(())
69+
/// }
70+
/// });
71+
/// assert_eq!(res, ControlFlow::Break(-1));
72+
/// assert_eq!(sum, 6);
4873
/// ```
4974
#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
5075
#[derive(Debug, Clone, Copy, PartialEq)]

0 commit comments

Comments
 (0)