Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I create a throwaway mutable reference?

Tags:

rust

I'm trying to wrap a vector to change its index behaviour, so that when an out of bounds access happens, instead of panicking it returns a reference to a dummy value, like so:

use std::ops::Index;

struct VecWrapper(Vec<()>);

impl Index<usize> for VecWrapper {
    type Output = ();
    fn index(&self, idx: usize) -> &() {
        if idx < self.0.len() {
            &self.0[idx]
        } else {
            &()
        }
    }
}

which works just fine for the implementation of Index, but trying to implement IndexMut the same way fails for obvious reasons. the type in my collection does not have a Drop implementation so no destructor needs to be called (other than freeing the memory).

the only solution I can think of is to have a static mutable array containing thousands of dummies, and distributing references to elements of this array, this is a horrible solution though it still leads to UB if there are ever more dummies borrowed than the size of the static array.

like image 330
terepy Avatar asked Sep 15 '25 08:09

terepy


1 Answers

Give the wrapper an additional field that's the dummy. It's got the same lifetime restrictions, and so can't be aliased.

like image 169
Sebastian Redl Avatar answered Sep 17 '25 22:09

Sebastian Redl