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 vectorvwith elements1,2, and3.let mut v_iter = v.iter();: creates an iteratorv_iterover the elements ofv.let borrowed_iter = v_iter.by_ref();: borrows the iteratorv_iterand 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 match a URL with a regex in Rust?
- How to make regex case insensitive in Rust?
- How to match the end of a line in a Rust regex?
- How to perform matrix operations in Rust?
- How to use binary regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex captures in Rust?
- How to get an entry from a HashSet in Rust?
- How to use regex builder in Rust?
- How to create a HashMap of structs in Rust?
See more codes...