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
- How to borrow with lifetime in Rust
- How to borrow vector element in Rust
- When to use borrow in Rust
- How to borrow from vector in Rust
- How to borrow hashmap in Rust
- How to borrow struct field in Rust
- How to borrow as static in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow moved value in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to parse JSON string in Rust?
- How to check if a Rust HashMap contains a key?
- How to convert a slice of bytes to a string in Rust?
- How to continue loop in Rust
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- Bitwise operator example in Rust
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
See more codes...