相关疑难解决方法(0)

有没有办法为多个特征创建一个类型别名?

我有一个通用函数,打印至少两个项目:

use std::fmt::Display;

fn print_min<T: PartialOrd + Display>(a: &T, b: &T) {
    println!("min = {}", if a < b { a } else { b });
}
Run Code Online (Sandbox Code Playgroud)

这适用于实现PartialOrdDisplay特征的任何东西:

print_min(&45, &46);
// min = 45
print_min(&"a", &"b");
// min = a
Run Code Online (Sandbox Code Playgroud)

必须放入PartialOrd + Display函数定义是一种丑陋的,特别是如果我想拥有一大堆对此进行操作的函数(例如,实现二进制搜索树),或者我的边界变得更复杂.我的第一个倾向是尝试编写一个类型别名:

type PartialDisplay = PartialOrd + Display;
Run Code Online (Sandbox Code Playgroud)

但这给了我一些相当奇怪的编译器错误:

error[E0393]: the type parameter `Rhs` must be explicitly specified
 --> src/main.rs:7:23
  |
7 | type PartialDisplay = PartialOrd + Display;
  |                       ^^^^^^^^^^ missing reference …
Run Code Online (Sandbox Code Playgroud)

rust

21
推荐指数
3
解决办法
2627
查看次数

标签 统计

rust ×1