Reputation: 6882
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.
Upvotes: 2
Views: 2207
Reputation: 2120
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());
}
Upvotes: 2
Reputation: 58735
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
Upvotes: 6