Pregunta

While programming a Sudoku Solver in Rust I had an issue with some code related to borrowing. While the issue was easy to solve (with a little bit of verbosity), it seemed very strange to me that the compiler didn't accept the first code.

It is difficult to explain what the problem is, so I have made a little example

use io::stdio::println;

struct Dog;
impl Dog {
    fn bark(&self, text: &str) {
        println(text);
    }

    fn get_text(&mut self) -> ~str {
        ~"some text"
    }
}

fn main() {
    let mut dog = Dog;

    // This causes an error
    dog.bark(dog.get_text());

    // But this is allowed
    let text = dog.get_text();
    dog.bark(text);
}

Is this a bug? If not, why does the borrow checker enforce coding this way?

¿Fue útil?

Solución

Yes, this is a bug: #6268.

The borrow checker doesn't seem to understand the arguments are fully evaluated by the time the original method is called and so thinks the &mut self of get_text is aliasing with the &self of bark (and having an aliasing &mut pointer is illegal).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top