Web*_*rix 2 reflection function rust
如何在我的函数中获取调用者类型?
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();
}
Run Code Online (Sandbox Code Playgroud)
这是操场上的工作代码。这是示例的简化代码。
Rust 没有像这样内置的任何机器。如果您想了解函数内的某些上下文,则需要将其作为参数传入。
此外,Rust 无法获取类型的名称,因此您也必须提供该名称。例如,有一个特征:
trait Named {
fn name() -> &'static str;
}
impl Named for A {
fn name() -> &'static str {
"A"
}
}
Run Code Online (Sandbox Code Playgroud)
您可能会像这样使用:
impl B {
pub fn my_function<T: Named>(_: &T) {
println!("Hello");
println!("{}", T::name());
}
}
Run Code Online (Sandbox Code Playgroud)
你只需要在调用时传入调用者:
impl A {
fn call_function(&self) {
B::my_function(self);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
trait Named {
fn name() -> &'static str;
}
impl Named for A {
fn name() -> &'static str {
"A"
}
}
Run Code Online (Sandbox Code Playgroud)