我正在尝试编写一个函数,它接受一个泛型函数作为参数。参数(下面的processor
)应该在其参数上绑定一个特征。
fn process<P, T>(processor: &P)
where
P: Fn(&T),
T: ToString,
{
processor("foo");
}
fn processor<T>(x: &T)
where
T: ToString,
{
println!("{}", x.to_string());
}
fn main() {
process(&processor);
}
字符串
这会产生以下错误。如何修复代码?。
error[E0308]: mismatched types
--> src/main.rs:6:15
|
1 | fn process<P, T>(processor: &P)
| - this type parameter
...
6 | processor("foo");
| --------- ^^^^^ expected `&T`, found `&str`
| |
| arguments to this function are incorrect
|
= note: expected reference `&T`
found reference `&'static str`
note: callable defined here
--> src/main.rs:3:8
|
3 | P: Fn(&T),
| ^^^^^^
error[E0282]: type annotations needed
--> src/main.rs:17:14
|
17 | process(&processor);
| ^^^^^^^^^ cannot infer type of the type parameter `T` declared on the function `processor`
|
help: consider specifying the generic argument
|
17 | process(&processor::<T>);
| +++++
型
2条答案
按热度按时间aelbi1ox1#
你不能这么做
作为一个接近的替代方案,你可以定义一个trait:
字符串
7y4bm7vi2#
您可以在
&'static str
上添加另一个trait绑定,以便在将其传递给回调之前将其转换为T
:字符串
Playground.