Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Importing DerefMut and not Deref surprised me: I’ve never done it and never expect to, since you can’t implement DerefMut without implementing Deref. Turns out it was being imported to call it, which is something I’ve never done and never expect to: instead of writing `d.deref_mut()`, I’d write something like `&mut d` or `&mut **d`. (Autodereferencing makes the question of what asterisks are needed always a bit fun—but that largely applies to d.deref_mut() too: I think (*d).deref_mut() would produce the same result.)


This sort of thing is mostly a matter of preference; Rust does a good job being unopinionated about things like how you invoke a function. In this particular case I think the explicit call is more readable than the character-soup, personally


I think it might be trying to get at “dereferencing this does something special” (i.e. it’s not just a reference, but some type that manually implements Deref/DerefMut). But it doesn’t actually do that—if you have a &mut String, .deref_mut() will give a &mut str (equivalent to &mut *self), but if you have a &mut str, .deref_mut() will give a &mut str too, by doing reference reborrowing (so the final result is equivalent to &mut **self).

In the end, I’d prefer to deal with the sigils, because I think it’s a little easier to be confident what they’re going to do than calling the method that takes &mut self but effectively changes how it behaves depending on the type in question.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: