MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / remove

Method remove

code/chapter05/hashmap.rs:60–94  ·  view source on GitHub ↗
(&mut self, key: usize)

Source from the content-addressed store, hash-verified

58 }
59
60 fn remove(&mut self, key: usize) -> Option<T> {
61 if 0 == key { panic!("Error: key must > 0"); }
62
63 let pos = self.hash(key);
64 if 0 == self.slot[pos] { // 槽中无数据,返回 None
65 None
66 } else if key == self.slot[pos] {
67 self.slot[pos] = 0; // 找到相同 key,更新 slot 和 data
68 let data = Some(self.data[pos].clone());
69 self.data[pos] = Default::default();
70 data
71 } else {
72 let mut data: Option<T> = None;
73 let mut stop = false;
74 let mut found = false;
75 let mut curr = pos;
76
77 while 0 != self.slot[curr] && !found && !stop {
78 if key == self.slot[curr] { // 找到了值,删除数据
79 found = true;
80 self.slot[curr] = 0;
81 data = Some(self.data[curr].clone());
82 self.data[curr] = Default::default();
83 } else {
84 // 再哈希回到最初位置,说明找了一圈还没有
85 curr = self.rehash(curr);
86 if curr == pos {
87 stop = true;
88 }
89 }
90 }
91
92 data
93 }
94 }
95
96 fn get(&self, key: usize) -> Option<&T> {
97 if 0 == key { panic!("Error: key must > 0"); }

Callers

nothing calls this directly

Calls 2

hashMethod · 0.45
rehashMethod · 0.45

Tested by

no test coverage detected