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

后端 未结 1 1096
暖寄归人
暖寄归人 2020-12-19 00:06

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

相关标签:
1条回答
  • 2020-12-19 00:36

    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);
    }
    
    0 讨论(0)
提交回复
热议问题