rustHow to borrow iterator in Rust
To borrow an iterator in Rust, you can use the Iterator::by_ref
method. This method returns an iterator that borrows the original iterator.
let v = vec![1, 2, 3];
let mut v_iter = v.iter();
let borrowed_iter = v_iter.by_ref();
for i in borrowed_iter {
println!("{}", i);
}
Output example
1
2
3
The code above borrows the iterator v_iter
and stores it in borrowed_iter
. The for
loop then iterates over borrowed_iter
and prints out the elements.
Code explanation
let v = vec![1, 2, 3];
: creates a vectorv
with elements1
,2
, and3
.let mut v_iter = v.iter();
: creates an iteratorv_iter
over the elements ofv
.let borrowed_iter = v_iter.by_ref();
: borrows the iteratorv_iter
and stores it inborrowed_iter
.for i in borrowed_iter {
: iterates overborrowed_iter
.println!("{}", i);
: prints out the elements ofborrowed_iter
.
Helpful links
Related
More of Rust
- How to convert a Rust HashMap to a BTreeMap?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to use the global flag in a Rust regex?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to use 'or' in Rust regex?
- How to use non-capturing groups in Rust regex?
See more codes...