简体   繁体   English

如何使用反射使用一些参数调用未知的Rust函数?

[英]How can I invoke an unknown Rust function with some arguments using reflection?

I'm having a lot of fun playing around with Rust having been a C# programmer for a long time but I have a question around reflection. 在Rust担任C#程序员很长时间的过程中,我玩得很开心,但是我对反射存在疑问。 Maybe I don't need reflection in this case but given that Rust is strongly typed I suspect I do (I would definitely need it in good ol' C#, bless its cotton socks). 在这种情况下,也许我不需要反思,但是考虑到Rust是强类型的,我怀疑我确实需要这样做(我肯定会在C#良好的情况下使用它,祝福它的棉袜)。

I have this situation: 我有这种情况:

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
}

How would I do that? 我该怎么做? I'm guessing I need to pass in some sort of MethodInfo as the second argument to the function and then poke around with that to get the arguments whose name is the key in the hash map and assign the values but I had a look around for the reflection API and found the following pre-Rust 1.0 documentation: 我猜想我需要将某种MethodInfo作为函数的第二个参数传递,然后在其中进行查找以获取名称是哈希图中的键的参数并分配值,但是我四处寻找反射API,并找到以下Rust 1.0以前的文档:

None of these give me enough to go on to get started. 这些都给我不足以继续上手。 How would I implement the function I describe above? 我将如何实现上述功能?

Traits are the expected way to implement a fair amount of what reflection is (ab)used for elsewhere. 特质是实现相当数量的(滥用)在其他地方使用的反射的预期方式。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM