在Rust中是否可以反射,如果是这样,我如何使用一些参数调用未知函数?

kmp*_*kmp 11 reflection rust

我很开心玩Rust很长一段时间都是C#程序员,但我对反思有疑问.

嗯,我认为反思,也许我不需要在这种情况下进行反思,但鉴于Rust是强烈打字我怀疑我做的(我肯定需要它在好的'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
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办?我猜我需要传递一些MethodInfo作为函数的第二个参数,然后用它来解决它的名字是哈希映射中的键的参数并分配值,但我看了一下反射API并发现以下内容:

但他们都没有给我足够的继续开始.那么,我将如何实现上面描述的功能呢?

Sea*_*rry 7

特征是实现大量反射(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);
}
Run Code Online (Sandbox Code Playgroud)