There are indeed close-to-official guidelines related with Deref
and DerefMut
. According to C-DEREF from the Rust API guidelines, "Only smart pointers implement Deref
and DerefMut
." Your suggestion to use Deref
would lead to multiple issues, and so it is strongly unadvised.
Deref
does not have a type parameter, but an associated type. Implementing it would have to be done as the code below, but could never be implemented for additional attributes.
// don't try this at home!
impl Deref for IdAndUrl {
type Target = Id;
fn deref(&self) -> &Self::Target { &self.id }
}
Moreover, a Deref
implementation exposes the methods from the target type via deref coercion, polluting the struct with an interface that you might not want to have here.
One could look at the other conversion traits (namely From
, AsRef
, and Borrow
) and see if they make sense (C-CONV-TRAITS). But from my interpretation, none of these would make sense. As already suggested in another answer, a simple getter is ideal here:
impl IdAndUrl {
fn id(&self) -> &Id { &self.id }
}