To Deref or not to Deref?


#1

Hi there,

I’m writing a wrapper type for integer/float types to make them work like Option, at the cost of having one None-value.

Now I am unsure whether to impl Deref for my type where target=Option<T> – on one hand, it should make the conversion automatic and make for nicer looking code, on the other hand it would probably slow down compilation (as the type inference has to insert the derefs) and make for some puzzler, as it is no longer clear, where the coercion takes place.

What do you think? Should I impl Deref or just From/Into?


#2

If implementing Deref can be done without creating something new on the stack, then in this case you should implement it. However, if your wrapper type just contains a single integer or float variable, I don’t think it would be possible to implement Deref at all.

To implement deref, you have to have some method fn deref(&self) -> &Option<T> - You have to have an Option (or something equivalent in memory layout) stored inside your struct - rust won’t ever let you create a new option inside a method and then try to return a reference to it.

In summary: if you can find a way to implement Deref for your type, go for it. It seems pretty much impossible to do though for your specific case.


#3

Thank you so much – you cleared up a misconception I had regarding Deref.

In fact I can implement Deref<Target=Option<bool>> for OptionBool using constant &Some(true), &Some(false) and None.

Someone should really blog about what the various traits (Borrow, ToOwned, AsRef, Deref, From, Into, etc.) are, how they work together and when to implement them.

That someone could well be me, but first I’ll have to understand them :smile: