Impl From<&Cow<[T]>> for &[T]

Is there a fundamental reason that impl From<&Cow<[T]>> for &[T] does not exist?

This would be marginally useful for some generic code. Right now, I'm making the generic code generic over the conversion function FnOnce(T) -> R (which could arguably be seen as better, but if I could get away with T: Into<R>, it would have been simpler).

This particular implementation exists as Deref, AsRef and Borrow implementations on Cow. Maybe one of those traits would give you the generic behaviour you need?

I don't think there's a fundamental obstacle to implementing From on references when you can implement Deref on the references' targets (but it would have to be done one type at a time, rather than as a blanket implementation, both for coherence reasons and to handle weird situations like a type that Derefs into itself) – the implementation itself would be valid on its own, so the only potential problem would be conflicting trait definitions.

3 Likes

I need both reflexivity without being under a reference and this &Cow<[u8]> to &[u8]. So it seems none of those options would work.

impl AsRef<[u8]> and where &T: AsRef<[u8]>, T: ?Sized work, but only if you don't need a specific lifetime.

I think you could make a PR to the standard library. Often such implementations are missing simply because nobody asked for them yet. If it overlaps with some other From, at least the build error will tell you why.

impl AsRef<[u8]> and where &T: AsRef<[u8]>, T: ?Sized work, but only if you don't need a specific lifetime.

I think you could make a PR to the standard library. Often such implementations are missing simply because nobody asked for them yet. If it overlaps with some other From, at least the build error will tell you why.


It's annoying that libstd has so many borrowing traits, but none of them take a lifetime. AFAIK there's no way to ask for a generic T that can lend something for a specific &'a lifetime.