I am attempting to create a struct in Rust that has two methods. One method should return the item at the current position in a list, and the other method should move the current position to the next item and return the last item. The code I have written is as follows:
struct Item {
value: i32,
}
struct A {
position: usize,
list: Vec<Item>,
}
impl A {
fn current(&self) -> &Item {
&self.list[self.position]
}
fn next(&mut self) -> &Item {
let bar = self.current();
self.position += 1;
bar
}
}
fn main() {
let mut a = A { position: 0, list: vec![Item { value: 1 }] };
a.next();
}
However, I am encountering this error when I try to compile it:
error[E0506]: cannot assign to `self.position` because it is borrowed
--> src/main.rs:17:9
|
15 | fn next(&mut self) -> &Item {
| - let's call the lifetime of this reference `'1`
16 | let bar = self.current();
| -------------- `self.position` is borrowed here
17 | self.position += 1;
| ^^^^^^^^^^^^^^^^^^ `self.position` is assigned to here but it was already borrowed
18 | bar
| --- returning this value requires that `*self` is borrowed for `'1`
For more information about this error, try `rustc --explain E0506`.
error: could not compile `playground` (bin "playground") due to previous error
I don't believe that I borrowed self.position
because I used it directly as an array index. Can you help me understand what mistake I made? Thank you in advance.