有没有办法为多个特征创建类型别名? [英] Is there any way to create a type alias for multiple traits?

查看:38
本文介绍了有没有办法为多个特征创建类型别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用函数,可以打印两个项目中的最小值:

I have a generic function that prints the minimum of two items:

use std::fmt::Display;

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

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

This works pretty well with anything that implements both the PartialOrd and Display traits:

print_min(&45, &46);
// min = 45
print_min(&"a", &"b");
// min = a

必须将 PartialOrd + Display 放在函数定义中有点难看,特别是如果我想有一大堆函数来操作它(例如,实现二叉搜索树),或者如果我的界限变得更复杂.我的第一个倾向是尝试编写一个类型别名:

Having to put the PartialOrd + Display in the function definition is kind of ugly, especially if I want to have a whole bunch of functions that operate on this (implementing a binary search tree, for example), or if my bounds get more complex. My first inclination was to attempt to write a type alias:

type PartialDisplay = PartialOrd + Display;

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

but this gives me some fairly bizarre compiler errors:

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

我猜要么是我的语法有误,要么目前还不可能.我想要类似的东西

I'm guessing either my syntax is wrong or this just isn't possible yet. I'd like something like

type PartialDisplay = ???
fn print_min<T: PartialDisplay> { /* ... */ }

推荐答案

PartialOrdDisplay 是特征.它已经讨论过如何实现别名,但最终决定不是'不需要.

PartialOrd and Display are traits. It has been discussed how to implement an alias but it was decided that it wasn't needed.

相反,您可以使用您想要的特征作为超级特征创建一个新特征,并提供一个全面的实现:

Instead, you can create a new trait with the traits you want as super traits and provide a blanket implementation:

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");
}

这篇关于有没有办法为多个特征创建类型别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆