gpt4 book ai didi

function - 如何在 Rust 中找到函数调用者的类型?

转载 作者:行者123 更新时间:2023-11-29 08:12:12 25 4
gpt4 key购买 nike

如何在我的函数中获取调用者类型?

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是 Playground 上的工作代码。这是示例的简化代码。

最佳答案

Rust 没有任何像这样内置的机制。如果您想知道函数内部的某些上下文,则需要将其作为参数传入。

此外,Rust 没有获取类型名称的方法,因此您也必须提供它。例如,具有特征:

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

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

你可以这样使用:

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

你只需要在调用它的时候传入调用者:

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

输出:

Hello
A

关于function - 如何在 Rust 中找到函数调用者的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51553065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com