如何在Rust中定义一个泛型函数,它接受一个带有trait绑定的泛型函数?

wj8zmpe1  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(166)

我正在尝试编写一个函数,它接受一个泛型函数作为参数。参数(下面的processor)应该在其参数上绑定一个特征。

  1. fn process<P, T>(processor: &P)
  2. where
  3. P: Fn(&T),
  4. T: ToString,
  5. {
  6. processor("foo");
  7. }
  8. fn processor<T>(x: &T)
  9. where
  10. T: ToString,
  11. {
  12. println!("{}", x.to_string());
  13. }
  14. fn main() {
  15. process(&processor);
  16. }

字符串
这会产生以下错误。如何修复代码?。

  1. error[E0308]: mismatched types
  2. --> src/main.rs:6:15
  3. |
  4. 1 | fn process<P, T>(processor: &P)
  5. | - this type parameter
  6. ...
  7. 6 | processor("foo");
  8. | --------- ^^^^^ expected `&T`, found `&str`
  9. | |
  10. | arguments to this function are incorrect
  11. |
  12. = note: expected reference `&T`
  13. found reference `&'static str`
  14. note: callable defined here
  15. --> src/main.rs:3:8
  16. |
  17. 3 | P: Fn(&T),
  18. | ^^^^^^
  19. error[E0282]: type annotations needed
  20. --> src/main.rs:17:14
  21. |
  22. 17 | process(&processor);
  23. | ^^^^^^^^^ cannot infer type of the type parameter `T` declared on the function `processor`
  24. |
  25. help: consider specifying the generic argument
  26. |
  27. 17 | process(&processor::<T>);
  28. | +++++

aelbi1ox

aelbi1ox1#

你不能这么做
作为一个接近的替代方案,你可以定义一个trait:

  1. trait Processor {
  2. fn process<T: ToString + ?Sized>(&self, v: &T);
  3. }
  4. fn process<P>(processor: &P)
  5. where
  6. P: Processor,
  7. {
  8. processor.process("foo");
  9. }
  10. struct MyProcessor;
  11. impl Processor for MyProcessor {
  12. fn process<T: ToString + ?Sized>(&self, x: &T) {
  13. println!("{}", x.to_string());
  14. }
  15. }
  16. fn main() {
  17. process(&MyProcessor);
  18. }

字符串

展开查看全部
7y4bm7vi

7y4bm7vi2#

您可以在&'static str上添加另一个trait绑定,以便在将其传递给回调之前将其转换为T

  1. fn process<P, T>(processor: &P)
  2. where
  3. P: Fn(&T),
  4. T: ToString,
  5. &'static str: Into<T>,
  6. {
  7. processor(&"foo".into());
  8. }
  9. fn processor<T>(x: &T)
  10. where
  11. T: ToString,
  12. {
  13. println!("{}", x.to_string());
  14. }
  15. fn main() {
  16. process(&processor::<&str>);
  17. }

字符串
Playground.

展开查看全部

相关问题