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
3The 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 vector- vwith elements- 1,- 2, and- 3.
- let mut v_iter = v.iter();: creates an iterator- v_iterover the elements of- v.
- let borrowed_iter = v_iter.by_ref();: borrows the iterator- v_iterand stores it in- borrowed_iter.
- for i in borrowed_iter {: iterates over- borrowed_iter.
- println!("{}", i);: prints out the elements of- borrowed_iter.
Helpful links
Related
- How to borrow struct field in Rust
- How to borrow moved value in Rust
- How to borrow int in Rust
- How to borrow hashmap in Rust
- How to borrow from iterator in Rust
- How to borrow from vector in Rust
- How to borrow with lifetime in Rust
- When to use borrow in Rust
- How to borrow vector element in Rust
- Rust unsafe borrow example
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex captures in Rust?
- How to use non-capturing groups in Rust regex?
- How to replace all using regex in Rust?
- How to print a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to replace strings using Rust regex?
See more codes...