@@ -1993,6 +1993,31 @@ pub trait Iterator {
1993
1993
/// assert_eq!(it.len(), 2);
1994
1994
/// assert_eq!(it.next(), Some(&40));
1995
1995
/// ```
1996
+ ///
1997
+ /// While you cannot `break` from a closure, the [`crate::ops::ControlFlow`]
1998
+ /// type allows a similar idea:
1999
+ ///
2000
+ /// ```
2001
+ /// use std::ops::ControlFlow;
2002
+ ///
2003
+ /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2004
+ /// if let Some(next) = prev.checked_add(x) {
2005
+ /// ControlFlow::Continue(next)
2006
+ /// } else {
2007
+ /// ControlFlow::Break(prev)
2008
+ /// }
2009
+ /// });
2010
+ /// assert_eq!(triangular, ControlFlow::Break(120));
2011
+ ///
2012
+ /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2013
+ /// if let Some(next) = prev.checked_add(x) {
2014
+ /// ControlFlow::Continue(next)
2015
+ /// } else {
2016
+ /// ControlFlow::Break(prev)
2017
+ /// }
2018
+ /// });
2019
+ /// assert_eq!(triangular, ControlFlow::Continue(435));
2020
+ /// ```
1996
2021
#[ inline]
1997
2022
#[ stable( feature = "iterator_try_fold" , since = "1.27.0" ) ]
1998
2023
fn try_fold < B , F , R > ( & mut self , init : B , mut f : F ) -> R
@@ -2035,6 +2060,22 @@ pub trait Iterator {
2035
2060
/// // It short-circuited, so the remaining items are still in the iterator:
2036
2061
/// assert_eq!(it.next(), Some("stale_bread.json"));
2037
2062
/// ```
2063
+ ///
2064
+ /// The [`crate::ops::ControlFlow`] type can be used with this method for the
2065
+ /// situations in which you'd use `break` and `continue` in a normal loop:
2066
+ ///
2067
+ /// ```
2068
+ /// use std::ops::ControlFlow;
2069
+ ///
2070
+ /// let r = (2..100).try_for_each(|x| {
2071
+ /// if 323 % x == 0 {
2072
+ /// return ControlFlow::Break(x)
2073
+ /// }
2074
+ ///
2075
+ /// ControlFlow::Continue(())
2076
+ /// });
2077
+ /// assert_eq!(r, ControlFlow::Break(17));
2078
+ /// ```
2038
2079
#[ inline]
2039
2080
#[ stable( feature = "iterator_try_fold" , since = "1.27.0" ) ]
2040
2081
fn try_for_each < F , R > ( & mut self , f : F ) -> R
0 commit comments