1

It is possible to make a call to a specific implementation of a generic method on a struct, ex:

impl Printer<i16> {
    pub fn run() { println!("Specific i16"); }
}

Printer::<i16>::run();

It is also possible to make a blanket, default implementation of that method, ex:

trait Blanket<T: Printable> {
    fn run() { println!("Blanket"); }
}

impl<T: Printable> Blanket<T> for Printer<T> {}

Why is it that attempting to call the specific implementation from a generic function does not work?

fn generic_run<T: Printable>() {
    Printer::<T>::run();
}

generic_run::<i16>::(); // Prints "Blanket"

Is there a way to allow a generic function to dispatch to specific implementations?

Playground

0

1 Answer 1

2

Your "specific" implementation is just an inherent method on Printer<i16>, which has nothing to do with the method on Blanket. The fact that an inherent method shares name with a method defined by the trait won't make generic code that depends on the trait invoke the inherent method - Rust generics aren't "duck typed" like that. The feature that would enable1 what you're looking for is called specialization, and is experimentally available in nightly Rust. Unfortunately the experiment has a number of issues and won't make it into stable Rust any time soon.

In the meantime, in simpler cases you can emulate specialization using TypeId::of(). For example, defining Blanket::run() like this results in the expected output of "Blanket" followed by twice "Specific - i16":

use std::any::{Any, TypeId};

// ...Printable and generic_run() defined as before...

trait Blanket<T: Printable> {
    fn run() {
        if TypeId::of::<T>() == TypeId::of::<i16>() {
            return Printer::<i16>::run();
        }
        println!("Blanket");
    }
}

Playground

In the above code you can expect the == check to be optimized away in release builds because, due to monomorphization, the compiler knows the type of T when generating the code for a specific Blanket::<T>::run().


1 Even the unstable specialization still doesn't allow C++ style "duck typing" of generic code - see here or here for examples of how it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.