A blanket implementation for Into<Cow>

#1

I’ve been writing a lot of functions that have parameters with the type impl Into<Cow<'a, T>>, as these functions need to take ownership of the value, but it’s messy to have .clone() dotted around in the places that call these functions.

Unfortunately, not many external types implement Into<Cow>. While my knowledge of Rust is still limited, it seems to me this could be automatically implemented with:

impl<'a, T: ToOwned> From<&'a T> for Cow<'a, T> {
    fn from(x: &'a T) -> Cow<'a, T> {
        Cow::Borrowed(x)
    }
}

impl<'a, T: ToOwned> From<T> for Cow<'a, T> {
    fn from(x: T) -> Cow<'a, T> {
        Cow::Owned(x)
    }
}

I assume I’m missing an obvious reason why this isn’t in the standard library, but otherwise it would be nice to see it there.

1 Like
#2

These two impls conflict.

imo writing Cow::Borrowed or Cow::Owned isn’t that bad.

You could impl Into for the types that you want to convert into a Cow if you want that behaviour.

Also, shouldn’t the second impl be impl<'a, T: ToOwned> From<T::Owned> for Cow<'a, T> (this would still conflict)


playground link This playground link uses a copy of Cow, so there are no other impls on it besides the two you provided to show that they conflict.

#3

Thanks for your reply KrishnaSannasi, I think I’m going to start a separate thread about the problem more generally.