I've been working on a platformer game in rust. Game objects are stored in a Vec, and each is updated independently. However, a given object would like to interact with other objects. In C I would do something like fn update(&mut self, others: &mut [Self]). However, this would result in the parameters being aliased, which is not allowed.

What I'm looking for is some type that acts like a &mut [T], but remembers which element it is not allowed to access. I could use two &mut [T] values, built with split_at_mut, but this is unwieldy. I could make a struct that contains both. Is there a crate that does this? Ideally it would use unsafe internally so the compiler knows there is exactly one element in between. (that is to say, I would prefer something using only 24 bytes)

Chain does not do what I want because it can only be used as an iterator, not for indexing. To be clear, I would like to be able to index the result exactly like a &mut [T], except that it will find the element under consideration to be out of range.

you are viewing a single comment's thread
view the rest of the comments
[–] 11 points 4 days ago* (1 child)

classic. this has been a problem since the language was new.

the problem is that Rust is designed to not have this as a use case, or rather has machinery to make this marginally safer (mutexes etc) or make it unstable (panic) or just as unsafe as C (unsafe). if this is a pattern you want to maintain, Rust is going to throw friction at you by design, because tbh this pattern is the source of a ton of bugs.

it’s conceptually more complicated, but game engine devs have been moving to some form of Entity Component System[1] architecture, because it gives you a way to access memory that is both cache efficient and safe.

all that said i’m not a game dev. i think Bevy[2] was the blessed solution for a while?

1: https://en.wikipedia.org/wiki/Entity_component_system?wprov=sfti1 2: https://bevy.org/

  • source
  • hideshow 2 child comments
  • [–] 3 points 4 days ago (1 child)

    I don't think you need a mutex for this situation.

  • source
  • parent
  • hideshow 2 child comments
  • [–] 2 points 2 days ago* (1 child)

    I think you're right since a given object interacting with something else is commutative. As long as you iterate through all entities with a given set of components (all mobs against all collision borders) I'm pretty sure it doesn't matter what order you calculate them in even as long as you resolve it all by the next tick in the game world state. You're also only reading values from many places and updating one value with the variable that owns it and can mutate it.

  • source
  • parent
  • hideshow 2 child comments