Distinguish generic method's instantiations


#1

Say I have generic method

pub foo<T>(t: T) { unimplemented!() }

Is there some way to distinguish in runtime between different instantiations of this method?


For you to understand why I need this, here is some context. Original problem is mocking generic methods. When I create mock for trait method, I create pair of methods: first one is stub method for struct implementing trait, second one is mock’s method generating expectation.

For example, given trait:

trait A { fn foo(&this, v: u32); }

following methods are generated:

impl A for AMock {
    fn foo(&this, v: u32) { ... }
}

and

impl AMock {
    fn foo_call<M0: Matcher<u32>>(&this, v: M0) -> Expectation<()> { ... }
}

However, this is problematic for generic methods, as I have to distinguish instantiations.
Supposing separate code is generated for each type I would use method address to distinguish between them, but how can I find relation between corresponding foo and foo_call instantiations?


#2

you can distinguish between generic method calls with the turbo fish syntax

trait CallMe { fn call(); }

impl CallMe for u32 { fn call() { println!("u32") } }
impl CallMe for f32 { fn call() { println!("f32") } }

fn call_me<T: CallMe>() { T::call(); }

call_me::<u32>();
call_me::<f32>();

will print

u32
f32

#3

You wrote how to call generic methods with specific type. My problem is get some runtime information about type parameters from inside that generic method.

fn call_me<T> { ... }  // Implementation is the question

call_me::<u32>(); // Should print "u32" or some type info hash, anything,
                  // but that value must be same for all invocations with same type
                  // parameter and must differ from value in invocations with
                  // different type parameters

#4

std::any::TypeId.


#5

Oh, i misunderstood