Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

rust - Is there any way to create a type alias for multiple traits?

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

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

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> { /* ... */ }
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...