@@ -216,6 +216,43 @@ impl<I: Iterator> Peekable<I> {
216
216
self . peeked . get_or_insert_with ( || iter. next ( ) ) . as_ref ( )
217
217
}
218
218
219
+ /// Returns a mutable reference to the next() value without advancing the iterator.
220
+ ///
221
+ /// Like [`next`], if there is a value, it is wrapped in a `Some(T)`.
222
+ /// But if the iteration is over, `None` is returned.
223
+ ///
224
+ /// Because `peek_mut()` returns a reference, and many iterators iterate over
225
+ /// references, there can be a possibly confusing situation where the
226
+ /// return value is a double reference. You can see this effect in the examples
227
+ /// below.
228
+ ///
229
+ /// [`next`]: Iterator::next
230
+ ///
231
+ /// # Examples
232
+ ///
233
+ /// ```
234
+ /// #![feature(peekable_peek_mut)]
235
+ /// let mut iter = [1, 2, 3].iter().peekable();
236
+ ///
237
+ /// assert_eq!(iter.peek_mut(), Some(&mut &1));
238
+ /// assert_eq!(iter.next(), Some(&1));
239
+ ///
240
+ /// // Peek into the iterator and modify the value which will be returned next
241
+ /// if let Some(mut p) = iter.peek_mut() {
242
+ /// if *p == &2 {
243
+ /// *p = &5;
244
+ /// }
245
+ /// }
246
+ ///
247
+ /// assert_eq!(iter.collect::<Vec<_>>(), vec![&5, &3]);
248
+ /// ```
249
+ #[ inline]
250
+ #[ unstable( feature = "peekable_peek_mut" , issue = "78302" ) ]
251
+ pub fn peek_mut ( & mut self ) -> Option < & mut I :: Item > {
252
+ let iter = & mut self . iter ;
253
+ self . peeked . get_or_insert_with ( || iter. next ( ) ) . as_mut ( )
254
+ }
255
+
219
256
/// Consume and return the next value of this iterator if a condition is true.
220
257
///
221
258
/// If `func` returns `true` for the next value of this iterator, consume and return it.
0 commit comments