I can write a function which accepts X
and &X
:
fn foo<T: Borrow<X>>(x: T)
I can write a function which accepts X
, Y
and &Y
, assuming the Into
trait is implemented on Borrow<Y>
:
fn foo<T: Into<X>>(x: T)
Is there a way to write a function which accepts X
, &X
, Y
and &Y
using only standard traits? I can do it using custom traits, but using standard ones would be much better.
I tried:
use std::borrow::Borrow;
fn foo<TT: Into<T>, T: Borrow<X>>(x: TT) {}
struct X;
fn main() {
foo(X);
}
But I get:
error[E0283]: type annotations required: cannot resolve `_: std::borrow::Borrow<X>`
--> src/main.rs:8:5
|
8 | foo(X);
| ^^^
|
= note: required by `foo`
This is disallowed because there's the possibility of multiple paths. For example, the type passed in might implement
Into<A>
andInto<B>
. If bothA
andB
implementBorrow<X>
, it would be ambiguous which conversion would be appropriate.As the error message states, you can use type annotations (a.k.a. the turbofish) to tell the compiler which intermediate type you wish to convert into: