TSK
TSK

Reputation: 751

Implement `AsRef` and `Borrow` on `Cow`

In the standard library, Cow implements AsRef and Borrow in different ways.

In AsRef it returns self:

impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
    fn as_ref(&self) -> &T {
        self
    }
}

In Borrow it returns &**self:

impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
where
    B: ToOwned,
    <B as ToOwned>::Owned: 'a,
{
    fn borrow(&self) -> &B {
        &**self
    }
}

Is this difference very important?

Upvotes: 3

Views: 258

Answers (1)

kmdreko
kmdreko

Reputation: 60447

There is not a significant difference between the two, they could be swapped without any issue. The first uses an implicit deref coercion and the second uses an explicit dereference. Both are able to convert &Cow<'_, T> to &T because Cow implements Deref.

Upvotes: 4

Related Questions