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

use std::collections::BTreeMap;


#[derive(Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
enum Expression {
    String(StringObj),
    HashLiteral(HashLiteral),
}


#[derive(Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
struct StringObj {
    value: String,
}


#[derive(Debug, Eq, Hash,PartialEq, Ord, PartialOrd)]
struct HashLiteral {
    pair: BTreeMap<Expression, Expression>,
}


fn main() {
    let mut hash_literal = HashLiteral {
        pair: BTreeMap::new(),
    };
    
    hash_literal.pair.insert(Expression::String(StringObj {
        value: "1".to_string(),
    }), Expression::String(StringObj {
        value: "2".to_string(),
    }));
    
    let mut temp_hash_map = BTreeMap::new();
    temp_hash_map.insert(Expression::String(StringObj {
        value: "1".to_string(),
    }), Expression::String(StringObj {
        value: "2".to_string(),
    }));
    
    hash_literal.pair.insert(Expression::String(StringObj {
        value: "3".to_string(),
    }), Expression::HashLiteral(HashLiteral {
        pair: temp_hash_map,
    }));
    
    println!("hash_literal = {:#?}", hash_literal);
}

@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