Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.85 KB | None | 0 0
  1. extern crate owning_ref;
  2.  
  3. use std::collections::HashMap;
  4. use std::collections::hash_map::Entry;
  5.  
  6. use owning_ref::OwningRef;
  7.  
  8. struct Foo {
  9.     v: OwningRef<String, str>,
  10.     // Other data not important for the question
  11. }
  12.  
  13. fn main() {
  14.     let mut l = Vec::<Foo>::new();
  15.     let mut hash = HashMap::<&str, usize>::new();
  16.  
  17.     for i in (0..10).chain((0..10).rev()) {    
  18.         let s = format!("aaa {}", i);
  19.         let s = OwningRef::new(s);
  20.         let foo = Foo { v: s };
  21.         let sref = foo.v.as_ref();
  22.         let idx = match hash.entry(sref) { //a
  23.             Entry::Occupied(ent) => {
  24.                 *ent.get()
  25.             }
  26.             Entry::Vacant(ent) => {
  27.                 l.push(foo); //b
  28.                 ent.insert(l.len() - 1);
  29.                 l.len() - 1
  30.             }
  31.         };
  32.         // do something with idx
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement