5

ControlFlow in std::ops - Rust

 2 years ago
source link: https://doc.rust-lang.org/stable/std/ops/enum.ControlFlow.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Used to tell an operation whether it should exit early or go on as usual.

This is used when exposing things (like graph traversals or visitors) where you want the user to be able to choose whether to exit early. Having the enum makes it clearer – no more wondering “wait, what did false mean again?” – and allows including a value.

Examples

Early-exiting from Iterator::try_for_each:

use std::ops::ControlFlow;

let r = (2..100).try_for_each(|x| {
    if 403 % x == 0 {
        return ControlFlow::Break(x)
    }

    ControlFlow::Continue(())
});
assert_eq!(r, ControlFlow::Break(13));
Run

A basic tree traversal:

use std::ops::ControlFlow;

pub struct TreeNode<T> {
    value: T,
    left: Option<Box<TreeNode<T>>>,
    right: Option<Box<TreeNode<T>>>,
}

impl<T> TreeNode<T> {
    pub fn traverse_inorder<B>(&self, mut f: impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
        if let Some(left) = &self.left {
            left.traverse_inorder(&mut f)?;
        }
        f(&self.value)?;
        if let Some(right) = &self.right {
            right.traverse_inorder(&mut f)?;
        }
        ControlFlow::Continue(())
    }
}
Run

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK