Rust 如何将的引用传递到另一个函数?

Rust 如何将的引用传递到另一个函数?,rust,Rust,我有一个函数,它接受一个类型Into,假设我有一个Into的Vec,你如何调用它 以下是一些未能编译的示例代码: struct A {} struct B {} impl From<B> for A { fn from(value: B) -> A { A {} } } impl From<&B> for A { fn from(value: &B) -> A { A {}

我有一个函数,它接受一个类型
Into
,假设我有一个
Into
Vec
,你如何调用它

以下是一些未能编译的示例代码:

struct A {}

struct B {}

impl From<B> for A {
    fn from(value: B) -> A {
        A {}
    }
}

impl From<&B> for A {
    fn from(value: &B) -> A {
        A {}
    }
}

fn do_once<H: Into<A>>(item: H) {
    println!("do_once");
}

fn do_many<J: Into<A>>(items: Vec<J>) {
    let item = &items[0];
    do_once(item);
    
    // In the real code, we iterate here over all items.
}
struct A{}
结构B{}
从一个{
fn from(值:B)->A{
A{}
}
}
从一个{
fn from(值:&B)->A{
A{}
}
}
fn do_一次(项目:H){
println!(“做一次”);
}
fn多个(项目:Vec){
设项=&项[0];
做一次(项目);
//在实际代码中,我们在这里迭代所有项。
}
错误:

error[E0277]: the trait bound `A: From<&J>` is not satisfied
  --> src\main.rs:28:5
   |
22 | fn do_once<H: Into<A>>(item: H) {
   |               ------- required by this bound in `do_once`
...
28 |     do_once(item);
   |     ^^^^^^^ the trait `From<&J>` is not implemented for `A`
   |
   = note: required because of the requirements on the impl of `Into<A>` for `&J`
error[E0277]:未满足特性绑定'A:From'
-->src\main.rs:28:5
|
22 | fn do_一次(项目:H){
|----“do_once”中的此绑定要求`
...
28 |一次完成(项目);
|^^^^^^^未为` A'实现特性'From'`
|
=注:由于“&J”的“Into”impl要求,因此需要`
我认为问题在于我正在将
&传递到
,而不是将
传递到


除了更改do_once以接受
&H
而不是
H之外,还有什么其他解决方案吗?
在我的现实世界中,我想避免更改API。

是的,只需将特征边界移动一下,这样
&J
就成了
很棒的工作!不过我有一个问题,如果&J是In,J代表什么?这个函数的输入是一个Vec,如果之前它展示了一堆可以转化为a的东西,那么现在它代表了什么?
J
代表了一种类型,它的引用可以转化为类型
a
,所以基本上还是和以前一样。