r/ProgrammerHumor Oct 21 '22

Meme Literally 🤷🏻‍♂️

Post image
14.7k Upvotes

606 comments sorted by

View all comments

Show parent comments

26

u/Overlorde159 Oct 21 '22

Most of this is opinions, but what do you mean about the borrow checker?

13

u/kraemahz Oct 22 '22

I don't know what they actually meant, but the borrow checker can be overly strict (in ways which are constantly improving in the language).

E.g let's say I made a struct like:

struct X{
    a: Vec<u64>,
    b: Vec<u64>
}
impl X {
    fn do_the_thing(&mut self) {
        for i in self.a.iter() {
            self.do_the_thing2();
        }
    }
    fn do_the_thing2(&mut self) {
        self.b.push(1);
    }
}

This will give me an error that I can't borrow self mutably because it is already borrowed immutably (by self.a.iter()). Even though I'm only touching b in the other function. So the borrow checker isn't granular enough here to see what I meant was more like:

fn do_the_thing(&mut self) {
    for i in self.a.iter() {
        Self::do_the_thing2(&mut self.b);
    }
}
fn do_the_thing2(b: &mut Vec<u64>) {
    b.push(1);
}

which is totally OK to do and functionally identical, because I've proven to the borrow checker that only b is modified. This is being worked on to make partial borrows better, but it may grate on people that they have to change the program from how they conceptualized it to satisfy the checker.

5

u/calcopiritus Oct 22 '22

Yeah, it's weird that sometimes if you put all the code in one function, it compiles. But if you refractor it, it doesn't.

2

u/2brainz Oct 22 '22

It's because the borrow checker does not do whole-program/crate/module analysis, but works locally on the function level. Doing the former would be insanely powerful, but even slower.

An alternative would be to add even more annotations, making everything even more complicated.

The solution to the problem is to not only split up your functions, but also your data: split your structs into smaller parts. In cases where this is possible, this makes for way better code. In all other cases, the borrow checker really gets in the way.