rustHow to borrow from iterator in Rust
Rust provides a convenient way to borrow from an iterator using the .by_ref()
method. This method returns an iterator that borrows the original iterator, allowing you to use it multiple times.
let v = vec![1, 2, 3];
let mut iter = v.iter();
let first_borrow = iter.by_ref();
let second_borrow = iter.by_ref();
assert_eq!(Some(&1), first_borrow.next());
assert_eq!(Some(&2), second_borrow.next());
The output of the example code is:
assertion successful
assertion successful
The ## Code explanation
-
let v = vec![1, 2, 3];
: This line creates a vectorv
with elements1
,2
, and3
. -
let mut iter = v.iter();
: This line creates an iteratoriter
from the vectorv
. -
let first_borrow = iter.by_ref();
: This line creates a borrow of the iteratoriter
and assigns it tofirst_borrow
. -
let second_borrow = iter.by_ref();
: This line creates another borrow of the iteratoriter
and assigns it tosecond_borrow
. -
assert_eq!(Some(&1), first_borrow.next());
: This line asserts that the first element offirst_borrow
is1
. -
assert_eq!(Some(&2), second_borrow.next());
: This line asserts that the first element ofsecond_borrow
is2
.
Helpful links
Related
More of Rust
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to use regex to match a double quote in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
See more codes...