如何使用反射调用带有一些参数的未知 Rust 函数? [英] How can I invoke an unknown Rust function with some arguments using reflection?

查看:78
本文介绍了如何使用反射调用带有一些参数的未知 Rust 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 C# 程序员已经很长时间了,我在玩 Rust 时玩得很开心,但我有一个关于反射的问题.也许在这种情况下我不需要反射,但鉴于 Rust 是强类型的,我怀疑我需要(我肯定会在好的 C# 中需要它,祝福它的棉袜).

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. 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).

我有这种情况:

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 并找到了以下 Rust 1.0 之前的文档:

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:

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

None of these give me enough to go on to get started. How would I implement the function I describe above?

推荐答案

特征是实现相当数量的反射(ab)用于其他地方的预期方式.

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

这篇关于如何使用反射调用带有一些参数的未知 Rust 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆