Looking for trait between `Borrow` and `Deref`

I'm writing some code and I want to be generic over T, &T (and &mut T but mainly the first 2). It seems that the Borrow trait is the right choice, but I get an error when I use it because a single type can be Borrow<T> for multiple T. Is there a trait that works like Borrow, but has an associated type so the interence works and I can do Borrow<Target = Something>?

EDIT Deref doesn't work here because T !impl Deref<Target = T>.

No, associated types cannot both reference the type itself, and some dereferenced type. Those impls would overlap.

Is this for something like accepting both &str and String for the same function? The recommended answer here is to just take &str and accept that you sometimes have to write an & when calling it.

2 Likes

Sadly that's not an option for me. Thanks for the suggestion though.

The request fundamentally can't exist, because T is a method receiver for potentially many types through the deref chain, and T could itself be a reference &U, thus ambiguous whether it should project to &U or U.

That said, a more complete example of the inference error you're running into would be of assistance. Generally, taking impl AsRef<str> (for commonly supported AsRef types) interacts just fine with type inference, so you're likely doing something weird or overly generic that you don't need to.

5 Likes