Skip to content

Instantly share code, notes, and snippets.

@DaviRain-Su
Last active July 24, 2022 04:03
Show Gist options
  • Select an option

  • Save DaviRain-Su/47c96505d8332401ec53b8b02ea819ed to your computer and use it in GitHub Desktop.

Select an option

Save DaviRain-Su/47c96505d8332401ec53b8b02ea819ed to your computer and use it in GitHub Desktop.
Rust Learn
关于Map的使用在Rust中
@DaviRain-Su

Copy link
Copy Markdown
Author

Rust 中 Map中存放Callback的方法

use std::collections::BTreeMap;
use core::fmt::Debug;

fn main() {
    trait FuncCall: Debug {
        fn func_call(&self, print_str: &str) {
            println!("SELF is [{:?}], the result is {}", self, print_str);
        }
    }
    
    #[derive(Debug)]
    struct A;
    
    impl FuncCall for A {}
    
    #[derive(Debug)]
    struct B;
    
    impl FuncCall for B {}
    
    #[derive(Debug)]
    struct C;
    
    impl FuncCall for C {}
    
    
     let mut map_function = BTreeMap::<&str, Box<dyn FuncCall>>::new();
     
    map_function.insert("1", Box::new(A));
    map_function.insert("2", Box::new(B));
    map_function.insert("3", Box::new(C));
    

    for (key, value) in map_function.iter() {
        
        value.func_call(key);
    }
    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment