Advertisement
lyreinh

std-lib-types

Nov 28th, 2022 (edited)
1,415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 3.43 KB | Source Code | 0 0
  1. ### `HashMap`
  2. - Stores values by key, growable and shrinkable.
  3. - Any type impls the `Eq` and `Hash` trais can be a key. Includs:
  4.   - `bool` (not useful)
  5.   - `int`,`uint`, and all variantions thereof
  6.     - `f32` and `f64` donot have implement `Hash` as they might cause error
  7.   - `String` and `&str`
  8.     - Can have a `HashMap` keyed by `String` and call `.get()` with `&str`
  9. - Collection classes implement `Eq` and `Hash` if contained type impls.
  10. - Use `#[derive(PartialEq, Eq, Hash)]` for custom type
  11. - create a HashMap with a certain starting capacity using HashMap::with_capacity(uint), or use HashMap::new() to get a HashMap with a default initial capacity (recommended).
  12.  
  13. #### `HashSet`
  14. - Used when only keys are cared.(`HashSet<T>` wraps of `HashMap<T, ()>`)
  15. - Comparing to `Vec`, it donot have duplicate elements.
  16. - Sets have 4 primary operations: (all following calls return iterator)
  17.   - `union`: get all unique elements in both sets.
  18.   - `difference`: get all elements only in 1st set
  19.   - `intersection`: get all elements those are in both sets
  20.   - `symmetric_difference`: get all elements those are not in both sets.
  21.  
  22. ### `Rc` (Reference Counting)
  23. - Keeps track num of references (owner nums of value wrapped inside `Rc`)
  24. - Increase 1 when `Rc` is cloned, and decrease 1 when one clone is dropped
  25. - When `Rc` count becomes 0, both `Rc` and the value are all dropped.
  26.  
  27. ### `Arc` (Atomically Reference Counted)
  28. - For shared ownership between threads.
  29. - via `Clone`, create a ref pointer to heap value and increase ref count
  30. - The variable is dropped when all ref points go out of scope
  31.  
  32. ```rust
  33. use std::collections::HashMap;
  34.  
  35. // Eq requires that you derives PartialEq on the type
  36. #[derive(Eq, PartialEq, Hash)]
  37. struct Account<'a>
  38. {
  39.    username: <'a> &str,
  40.     password: <'a> &str,
  41. }
  42. struct AccountInfo<'a>
  43. {
  44.     name: <'a> &str,
  45.    email: <'a> &str,
  46. }
  47. type Accounts<'a> = HashMap<Account<'a>, AccountInfo<'a>);
  48. fn try_logon<'a>(accounts: &Accounts<'a>,
  49.                 username: &'a str, password: &'a str) {
  50.    println!("Username: {}"
  51. }
  52. fn call(number: &str) -> &str {
  53.    match number {
  54.        "798-1364" => "We're sorry, the call cannot be completed as dialed.
  55.             Please hang up and try again.",
  56.        "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
  57.            What can I get for you today?",
  58.        _ => "Hi! Who is this again?"
  59.    }
  60. }
  61.  
  62. fn main() {
  63.    let mut contacts = HashMap::new();
  64.  
  65.    contacts.insert("Daniel", "798-1364");
  66.    contacts.insert("Ashley", "645-7689");
  67.    contacts.insert("Katie", "435-8291");
  68.    contacts.insert("Robert", "956-1745");
  69.  
  70.    // Takes a reference and returns Option<&V>
  71.    match contacts.get(&"Daniel") {
  72.        Some(&number) => println!("Calling Daniel: {}", call(number)),
  73.        _ => println!("Don't have Daniel's number."),
  74.    }
  75.  
  76.    // `HashMap::insert()` returns `None`
  77.    // if the inserted value is new, `Some(value)` otherwise
  78.    contacts.insert("Daniel", "164-6743");
  79.  
  80.    match contacts.get(&"Ashley") {
  81.        Some(&number) => println!("Calling Ashley: {}", call(number)),
  82.        _ => println!("Don't have Ashley's number."),
  83.    }
  84.  
  85.    contacts.remove(&"Ashley");
  86.  
  87.    // `HashMap::iter()` returns an iterator that yields
  88.    // (&'a key, &'a value) pairs in arbitrary order.
  89.    for (contact, &number) in contacts.iter() {
  90.        println!("Calling {}: {}", contact, call(number));
  91.    }
  92. }
  93.  
  94. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement