Why can't I change a reference?

Now that I got all these reasons I finally understand. I also see now that this is actually not that far from the vec example after all. Its not about that the memory it points to is valid, but rather what value it points to. It could be a pain to debug something like that.

I also agree, that steepening the learning curve is not really helpful at this point.

Meanwhile I have encountered the reverse case:

struct Obj{
    v: Vec<i32>,
}

impl Obj{
    fn bla(&self){
        println!("bla");
    }
}

fn main() -> (){
    let mut obj = Obj{v: vec![34, 53, 11, 4]};
    obj.v.iter_mut().for_each(|it| {
        println!("val: {}", it);
        obj.bla();
        *it += 1;
    });
}

The obj is being burrowed mutably for the iterator. Inside the closure the same obj is being used immutably. How do I tell the compiler, that obj.bla() is safe to use? It won't affect the iterator in any way.
This of course is converted to its base issue.
In a real world application v corresponds to a buffer of pixels and bla() would make sure that the passed pixel is within bounds.

As far as I understand Cell won't help here, because I would need a get(), but Copy is not implemented. It wouldn't make sense to clone the whole struct anyway, because it would then clone the entire vector as well.

1 Like