Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

rust - Mutable self while reading from owner object

I have one object that owns another. The owned object has a mutating method that depends on non-mutating methods of its owner. The architecture (simplified as much as possible) looks like this:

struct World {
    animals: Vec<Animal>,
}

impl World {
    fn feed_all(&mut self) {
        for i in 0..self.animals.len() {
            self.animals[i].feed(self);
        }
    }
}

struct Animal {
    food: f32,
}

impl Animal {
    fn inc_food(&mut self) {
        self.food += 1.0;
    }

    fn feed(&mut self, world: &World) {
        // Imagine this is a much more complex calculation, involving many
        // queries to world.animals, several loops, and a bunch of if
        // statements. In other words, something so complex it can't just
        // be moved outside feed() and pass its result in as a pre-computed value.
        for other_animal in world.animals.iter() {
            self.food += 10.0 / (other_animal.food + self.food);
        }
    }
}

fn main() {
    let mut world = World {
        animals: Vec::with_capacity(1),
    };

    world.animals.push(Animal { food: 0.0 });

    world.feed_all();
}

The above does not compile. The compiler says:

error[E0502]: cannot borrow `*self` as immutable because `self.animals` is also borrowed as mutable
 --> src/main.rs:8:34
  |
8 |             self.animals[i].feed(self);
  |             ------------         ^^^^- mutable borrow ends here
  |             |                    |
  |             |                    immutable borrow occurs here
  |             mutable borrow occurs here

I understand why that error occurs, but what is the idiomatic Rust way to do this?

Just to be clear, the example code is not real. It's meant to present the core problem as simply as possible. The real application I'm writing is much more complex and has nothing to do with animals and feeding.

Assume it is not practical to pre-compute the food value before the call to feed(). In the real app, the method that's analogous to feed() makes many calls to the World object and does a lot of complex logic with the results.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'd want to compute the argument first in a form that doesn't alias self, then pass that in. As it stands, it seems a little strange that an animal decides how much food it's going to eat by looking at every other animal... regardless, you could add a method Animal::decide_feed_amount(&self, world: &World) -> f32. You can call that safely (&self and &World are both immutable, so that's OK), store the result in a variable, then pass that to Animal::feed.

Edit to address your Edit: well, you're kinda screwed, then. Rust's borrow checker is not sophisticated enough to prove that the mutations you make to the Animal cannot possibly interfere with any possible immutable access to the containing World. Some things you can try:

  • Do a functional-style update. Make a copy of the Animal you want to update so that it has its own lifetime, update it, then overwrite the original. If you duplicate the whole array up front, this gives you what is effectively an atomic update of the whole array.

    As someone who worked on a simulator for like half a decade, I wish I'd done something like that instead of mutating updates. sigh

  • Change to Vec<Option<Animal>> which will allow you to move (not copy) an Animal out of the array, mutate it, then put it back (see std::mem::replace). Downside is that now everything has to check to see if there's an animal in each position of the array.

  • Put the Animals inside Cells or RefCells, which will allow you to mutate them from immutable references. It does this by performing dynamic borrow checking which is infinitely slower (no checks vs. some checks), but is still "safe".

  • Absolute last resort: unsafe. But really, if you do that, you're throwing all your memory safety guarantees out the window, so I wouldn't recommend it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...