简体   繁体   中英

How to find the type of the caller of a function in Rust?

How can I get the caller type in my function?

struct A;
struct B;

impl A {
    fn new() -> Self {
        A
    }
    fn call_function(&self) {
        B::my_function();
    }
}

impl B {
    pub fn my_function() {
        println!("Hello");
        // println!("{}" type_of_the_caller) // I want to get type A here
        // Is it possible to get the caller type which is A in this case?
    }
}

fn main() {
    let a = A::new();
    a.call_function();
}

Here is the working code in playground. This is simplified code for an example.

Rust doesn't have any machinery like this built-in. If you want to know some context inside a function then you'll need to pass it in as an argument.

Also, Rust doesn't have a way to get the name of a type, so you'd have to provide that too. For example, with a trait:

trait Named {
    fn name() -> &'static str;
}

impl Named for A {
    fn name() -> &'static str {
        "A"
    }
}

Which you might use like this:

impl B {
    pub fn my_function<T: Named>(_: &T) {
        println!("Hello");
        println!("{}", T::name());
    }
}

You just have to pass in the caller when you call it:

impl A {
    fn call_function(&self) {
        B::my_function(self);
    }
}

Outputs:

Hello
A

You can have the compiler write the boilerplate by creating a macro and making use of the stringify! macro.

struct A;
struct B;
struct C;

trait Named {
    fn name() -> &'static str;
}

macro_rules! make_named {
    ( $($x:ty),* ) => {
        $(
        impl Named for $x {
            fn name() -> &'static str {
                stringify!($x)
            }
        }
        )*
    };
}

make_named!(A, B);
make_named!(C);

fn main() {
    println!("{:#?}", A::name());
    println!("{:#?}", B::name());
    println!("{:#?}", C::name());
}

playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM