DNNX
DNNX

Reputation: 6255

How to fix an error with borrowing peekable iterator twice in Rust?

TLDR

How to make the following code compile?

let mut iter = (1..3).peekable();
let h = iter.peek();
iter.next();

Update: I read How to use Rust's Peekable?, that is a different question because

  1. I don't even have a function here
  2. I don't have move out of dereference of error here

Long Story With Background

I'm trying to implement merging of two sorted "streams": I have two iterators both of which produce ordered values, and I need to print values of both of them, also ordered.

For example,

(1, 2, 20)
(3, 4, 5, 7)

should produce

(1, 2, 3, 4, 5, 7, 20)

The algorithm is simple I compare heads, then print the smaller head and advance the corresponding iterator.

The problem is that I can't wrap my head around lifetimes.

I have some initial implementation which isn't compiling. In order to make my question simpler to answer, I reduced my original implementation to the smallest possible example which fails with the same error as the original.

let mut iter = (1..3).peekable();
let h = iter.peek();
iter.next();

The error is

error[E0499]: cannot borrow `iter` as mutable more than once at a time
   --> src/main.rs:47:9
    |
44  |         let h = iter.peek();
    |                 ---- first mutable borrow occurs here
...
47  |         iter.next();
    |         ^^^^ second mutable borrow occurs here
...
114 | }
    | - first borrow ends here

How to fix this error?

I tried to do different things: adding mut, &, .by_ref() everywhere, but obviously, it didn't work because I have no idea what I'm doing.

Upvotes: 2

Views: 713

Answers (1)

NovaDenizen
NovaDenizen

Reputation: 5315

The Option::cloned(&self) method turns an Option<&T> into a Option<T>, given that T:Clone. It gets rid of the reference by making a copy of the value.

let mut iter = (1..3).peekable();
let h = iter.peek().cloned();
iter.next();

Upvotes: 1

Related Questions