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.

  • FizzyOrange@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    18 days ago

    I could use two &mut [T] values, built with split_at_mut, but this is unwieldy.

    This is likely to be the best option. You could wrap it in a nice interface that provides normal indexing but panics if you index the forbidden element. AI will be able to easily write that code for you.

      • FizzyOrange@programming.dev
        link
        fedilink
        arrow-up
        1
        ·
        13 days ago

        I think your intent sounds reasonable. I expect other people have done this, they probably just didn’t wrap it up in a nice crate.

        Also no idea why I was downvoted. Maybe because I mentioned the forbidden word.