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

use std::fmt::Display;

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

这对实现PartialOrdDisplay特性的任何东西都非常有效:

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> { /* ... */ }

推荐答案

PartialOrdDisplay是特征.它描述了如何实现别名,但决定不需要它.

相反,你可以创建一个新的trait ,将你想要的trait 作为超级trait ,并提供一个全面的实现:

use std::fmt::Display;

trait PartialDisplay: PartialOrd + Display {}
impl<T: PartialOrd + Display> PartialDisplay for T {}

fn print_min<T: PartialDisplay>(a: &T, b: &T) {
    println!("min = {}", if a < b { a } else { b });
}

fn main() {
    print_min(&45, &46);
    print_min(&"aa", &"bb");
}

Rust相关问答推荐

如何在Rust中获得高效的浮点最大值

从Rust调用C++虚拟方法即使在成功执行之后也会引发Access违规错误

如何找到一个数字在二维数组中的位置(S)?

我怎样才能从一个Rust 的日期中go 掉3年?

为什么我可以跟踪以前borrow 过的变量?房主在哪里?

如何正确地将App handler传递给Tauri中的其他模块?

为什么铁 rust S似乎有内在的易变性?

像这样的铁 rust 图案除了‘选项’之外,还有其他 Select 吗?

如何模拟/创建ReqData以测试Actix Web请求处理程序?

为什么基于高山Linux的Docker镜像不能在绝对路径下找到要执行的命令?

根据填充系数以相对大小在给定空间中布局项目

在 Rust 中,在需要引用 self 的 struct 体方法中使用闭包作为 while 循环条件

确保参数是编译时定义的字符串文字

如何限制 GtkColumnView 行数

Rust 如何返回大类型(优化前)?

为什么这段 Rust 代码会在没有递归或循环的情况下导致堆栈溢出?

(let b = MyBox(5 as *const u8); &b; ) 和 (let b = &MyBox(5 as *const u8); ) 之间有什么区别

强制特征仅在 Rust 中的给定类型大小上实现

如何将 while 循环内的用户输入添加到 Rust 中的向量?

如何在不设置精度的情况下打印浮点数时保持尾随零?