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
1.1k views
in Technique[技术] by (71.8m points)

rust - Generic implementation depending on traits

When defining a generic struct, is there a way in Rust to use different implementation of a method according to which trait is implemented by the given generic type T?

For example:

struct S<T> {
    value: T,
}

impl<T> S<T> {
    fn print_me(&self) {
        println!("I cannot be printed");
    }
}

impl<T: std::fmt::Display> S<T> {
    fn print_me(&self) {
        println!("{}", self.value);
    }
}

fn main() {
    let s = S { value: 2 };
    s.print_me();
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is an unstable feature known as specialization which permits multiple impl blocks to apply to the same type as long as one of the blocks is more specific than the other:

#![feature(specialization)]

struct Printer<T>(T);

trait Print {
    fn print(&self);
}

// specialized implementation
impl<T: fmt::Display> Print for Printer<T> {
    fn print(&self) {
        println!("{}", self.0);
    }
}

// default implementation
impl<T> Print for Printer<T> {
    default fn print(&self) {
        println!("I cannot be printed");
    }
}


struct NotDisplay;

fn main() {
    let not_printable = Printer(NotDisplay);
    let printable = Printer("Hello World");

    not_printable.print();
    printable.print();
}

// => I cannot be printed
// => Hello World

On stable Rust, we'll need some other mechanism to accomplish specialization. Rust has another language feature capable of doing this: method resolution autoref. The compiler's rule is that if a method can be dispatched without autoref then it will be. Only if a method cannot be dispatched without autoref, the compiler will insert an autoref and attempt to resolve it again. So in this example:

impl Print for Value {
    fn print(self) {
        println!("Called on Value");
    }
}

impl Print for &Value {
    fn print(self) {
        println!("Called on &Value");
    }
}

The implementation for Value will be prioritized over &Value. Knowing this rule, we can mimic specialization in stable Rust:

struct Printer<T>(T);

trait Print {
    fn print(&self);
}

// specialized implementation
impl<T: fmt::Display> Print for Printer<T> {
    fn print(&self) {
        println!("{}", self.0);
    }
}

trait DefaultPrint {
    fn print(&self);
}

// default implementation
//
// Note that the Self type of this impl is &Printer<T> and so the 
// method argument is actually &&T! 
// That makes this impl lower priority during method
// resolution than the implementation for `Print` above.
impl<T> DefaultPrint for &Printer<T> {
    fn print(&self) {
        println!("I cannot be printed");
    }
}

struct NotDisplay;

fn main() {
    let not_printable = Printer(NotDisplay);
    let printable = Printer("Hello World");
    
    (&not_printable).print();
    (&printable).print();
}

// => I cannot be printed
// => Hello World

The compiler will try to use the Print implementation first. If it can't (because the type is not Display), it will then use the more general implementation of DefaultPrint.

The way that this technique applies method resolution cannot be described by a trait bound, so it will not work for regular methods, as we would have to choose between one of the traits (DefaultPrint or Print):

fn print<T: ???>(value: T) {
    (&value).print()
}

However, this trick can be very useful to macros, which do not need to spell out trait bounds:

macro_rules! print {
    ($e:expr) => {
        (&$e).print()
    };
}


print!(not_printable); // => I cannot be printed
print!(printable); // => Hello World

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

...