Is there a way to write a function which accepts a

2019-08-24 03:25发布

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`

标签: rust
1条回答
聊天终结者
2楼-- · 2019-08-24 03:50

This is disallowed because there's the possibility of multiple paths. For example, the type passed in might implement Into<A> and Into<B>. If both A and B implement Borrow<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:

foo::<_, X>(X);
查看更多
登录 后发表回答