我有一个通用函数,可以打印至少两个项目:
use std::fmt::Display;
fn print_min<T: PartialOrd + Display>(a: &T, b: &T) {
println!("min = {}", if a < b { a } else { b });
}
这对实现PartialOrd
和Display
特性的任何东西都非常有效:
print_min(&45, &46);
// min = 45
print_min(&"a", &"b");
// min = a
必须在函数定义中加上PartialOrd + Display
有点难看,尤其是如果我想有一大堆函数在这上面运行(例如,实现一个二元搜索树),或者如果我的边界变得更复杂.我的第一个倾向是try 编写一个类型别名:
type PartialDisplay = PartialOrd + Display;
但这给了我一些相当奇怪的编译器错误:
error[E0393]: the type parameter `Rhs` must be explicitly specified
--> src/main.rs:7:23
|
7 | type PartialDisplay = PartialOrd + Display;
| ^^^^^^^^^^ missing reference to `Rhs`
|
= note: because of the default `Self` reference, type parameters must be specified on object types
error[E0225]: only auto traits can be used as additional traits in a trait object
--> src/main.rs:7:36
|
7 | type PartialDisplay = PartialOrd + Display;
| ^^^^^^^ non-auto additional trait
我猜要么是我的语法错了,要么就是这还不可能.我想要点
type PartialDisplay = ???
fn print_min<T: PartialDisplay> { /* ... */ }