我做了很长一段时间的C#程序员,在Rust上玩得很开心,但我有一个关于反思的问题.也许在这种情况下我不需要反射,但考虑到 rust 迹是强类型的,我怀疑我需要反射(我肯定需要它在好的ol'C#中,保佑它的棉袜子).

我有这样的情况:

use std::collections::HashMap;

fn invoke_an_unknown_function(
    hashmap: HashMap<String, String>,
    // Something to denote a function I know nothing about goes here
) {
    // For each key in the hash map, assign the value
    // to the parameter argument whose name is the key
    // and then invoke the function
}

我该怎么做?我猜我需要将某种类型的MethodInfo作为第二个参数传递给函数,然后用它来获取参数,这些参数的名称是散列图中的键,并分配值,但我查看了反射API,发现了以下pre-Rust 1.0文档:

这些都不足以让我开始.我将如何实现上述功能?

推荐答案

trait 是实现反射(ab)在其他地方使用的相当数量的预期方式.

trait SomeInterface {
    fn exposed1(&self, a: &str) -> bool;
    fn exposed2(&self, b: i32) -> i32;
}

struct Implementation1 {
    value: i32,
    has_foo: bool,
}

impl SomeInterface for Implementation1 {
    fn exposed1(&self, _a: &str) -> bool {
        self.has_foo
    }

    fn exposed2(&self, b: i32) -> i32 {
        self.value * b
    }
}

fn test_interface(obj: &dyn SomeInterface) {
    println!("{}", obj.exposed2(3));
}

fn main() {
    let impl1 = Implementation1 {
        value: 1,
        has_foo: false,
    };
    test_interface(&impl1);
}

Rust相关问答推荐

如何在不安全的代码中初始化枚举 struct

在actix—web中使用Redirect或NamedFile响应

有没有办法模仿对象安全克隆?

如何将`Join_all``Vec<;Result<;Vec<;Foo&>;,Anywhere::Error&>;`合并到`Result<;Vec<;Foo&>;,Anywhere::Error&>;`

值为可变对象的不可变HashMap

铁 rust 中的泛型:不能将`<;T作为添加>;::Output`除以`{Float}`

我可以在不收集或克隆的情况下,将一个带有Item=(key,val)的迭代器拆分成单独的key iter和val iter吗?

Rust 中什么时候可以返回函数生成的字符串切片&str?

从管道读取后重置标准输入

是否可以在不直接重复的情况下为许多特定类型实现一个函数?

Rust FFI 和 CUDA C 性能差异

在没有任何同步的情况下以非原子方式更新由宽松原子操作 Select 的值是否安全?

如何为已实现其他相关 std trait 的每个类型实现一个 std Trait

为什么Rust编译器会忽略模板参数应具有静态生命周期?

一旦令牌作为文字使用,声明宏不匹配硬编码值?

如何将这些测试放在一个单独的文件中?

Rust 引用元组和引用元组

为什么在 rust 中删除 vec 之前应该删除元素

从 Cranelift 发出 ASM

有没有更好的方法来为拥有 DIsplay 事物集合的 struct 实现 Display?