Borrowing self twice in a single expression sometimes leads to an error


This Content is from Stack Overflow. Question asked by rubo

The folliwing code fails to compile:

struct Foo {
    values: Vec<i32>,

impl Foo {
    fn len(&self) -> usize {
    fn set(&mut self) {
        self.values[self.len()] = 0;
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
  --> src/
12 |         self.values[self.len()] = 0;
   |         ------------^^^^^^^^^^-
   |         |           |
   |         |           immutable borrow occurs here
   |         mutable borrow occurs here
   |         mutable borrow later used here


There is a number of ways to fix this error, the most perplexing for me is this:

    fn set(&mut self) {
    fn set_len(&mut self, index: usize) {
        self.values[index] = 0;


Why does the first case fail to compile, while the second compiles? It seems to me that in both cases self is borrowed twice in a single expression – one time mutably, and one time immutably. Is there a subtle reason for this that I am unable to see, or is it a borrow checker quirk?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?