diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index 16bee0e2eee18..f7d09c23de023 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -174,9 +174,14 @@ pub trait DoubleEndedIterator: Iterator { /// ``` #[inline] #[stable(feature = "iter_nth_back", since = "1.37.0")] - fn nth_back(&mut self, n: usize) -> Option { - self.advance_back_by(n).ok()?; - self.next_back() + fn nth_back(&mut self, mut n: usize) -> Option { + for x in self.rev() { + if n == 0 { + return Some(x); + } + n -= 1; + } + None } /// This is the reverse version of [`Iterator::try_fold()`]: it takes diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 813afcc0ec6e4..b2e789adaf54a 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -363,9 +363,14 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn nth(&mut self, n: usize) -> Option { - self.advance_by(n).ok()?; - self.next() + fn nth(&mut self, mut n: usize) -> Option { + while let Some(x) = self.next() { + if n == 0 { + return Some(x); + } + n -= 1; + } + None } /// Creates an iterator starting at the same point, but stepping by