Should I use Borrow for a function that can take &[T] and &[&T]?

I’d like help writing a function signature. The function accepts a slice, and the elements of that slice should impl X. The catch is that I want the function to be able to accept a slice of owned values, or a slice of references. The following code works, but it feels like an awkward way to do it (implementing X twice):

impl X for T {}
impl<'a> X for &'a T {}
fn foo<T: X>(items: &[T])

Should I be using Borrow or AsRef instead?

Yeah, you can use AsRef or Borrow instead. If you use Borrow, you get a blanket impl<T> Borrow<T> for T from std; if you use AsRef, you’ll need to write it yourself (it’s trivial, of course). Say you decide to go with AsRef, then your signature could look like:

fn foo<T: X>(items: &[impl AsRef<T>])

That said, there’s nothing wrong, in and of itself, with implementing a trait for owned and borrowed variants of your type.

1 Like

Thank you!