Is there any way to create a type alias for multiple traits?
While awaiting the stabilization of trait aliasing, you can use the trait-set crate. Here is an example of its use:
trait-set! {
pub trait HashKey = Hash + Eq + Clone
}
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");
}
RFC 1733 introduced the concept of a trait alias. When it is stabilized, you will be able to say:
#![feature(trait_alias)]
use std::fmt::Display;
trait PartialDisplay<Rhs = Self> = PartialOrd<Rhs> + Display;
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(&"a", &"b");
}