Any way to make Index/Deref return a non-reference for types that implement Copy?

The official implementation of Deref states it returns a reference. E.g., from the example

impl Deref for DerefExample {
type Target = T;

fn deref(&self) -> &T {
    &self.value
}

}

Similarly for Index.

Is there a version (called something else?) in nightly that returns a T rather than a &T for types that implement Copy?

If I'm understanding the implications of the current interface correctly, forcing a &T is annoying.

Context: I want to wrap up external hardware memory on a micro-controller using Rust so I can Index it (cleanly!) as an array by overloading Index or as a struct and overload Deref, yet make sure every load and store uses read_volatile, write_volatile and does bounds checking. Right now, this won't work, b/c if I return a reference to the memory rustc will then generate code to access the referent using normal loads and stores.

But, hopefully I've misunderstood something, otherwise the Rust code is going to look significantly uglier than the C code would.

It looks like the alt-os volatile-ptr code might do what I need.
https://github.com/AltOS-Rust/volatile

However, it'd still be great to have a non &T index/deref!

1 Like

Bump.

If there is any progress on this, I'd be interested to hear about it.

There are many tricks (such as the volatile above) where you'd like to overload deref so you can do something fancy behind the scenes. The fact that you have to return a reference appears to preclude many of them. You can sort-of emulate C's volatile keyword by using this following clever but gross hack of inserting an asm statement to force the compiler reload values:

                    asm!("" ::: "memory" : "volatile");
                    return mem_location;   // hope that the rust compiler does not hoist this above / remove.

It'd be much cleaner, more reassuring to be able to just do:

                   return volatile_load(&mem_location)

But this doesn't work b/c you have to return a reference, not a value.

1 Like

This is a pretty common request and a serious wart in Rust right now (in my opinion). I'm pretty sure this is the RFC you're looking for:

https://github.com/rust-lang/rfcs/issues/997

1 Like

Sweet, thanks for the pointer! Hope it gets in nightly soon.

Any Copy type also implements Clone so for now you can call clone on the reference to get a value back.