pub struct Networks { /* private fields */ }Expand description
Interacting with network interfaces.
use sysinfo::Networks;
let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
println!("[{interface_name}]: {network:?}");
}Implementations§
Source§impl Networks
impl Networks
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty Networks type.
If you want it to be filled directly, take a look at Networks::new_with_refreshed_list.
use sysinfo::Networks;
let mut networks = Networks::new();
networks.refresh(true);
for (interface_name, network) in &networks {
println!("[{interface_name}]: {network:?}");
}Sourcepub fn new_with_refreshed_list() -> Self
pub fn new_with_refreshed_list() -> Self
Creates a new Networks type with the network interfaces
list loaded.
use sysinfo::Networks;
let networks = Networks::new_with_refreshed_list();
for network in &networks {
println!("{network:?}");
}Examples found in repository?
350fn main() {
351 println!("Getting system information...");
352 let mut system = System::new_all();
353 let mut networks = Networks::new_with_refreshed_list();
354 let mut disks = Disks::new_with_refreshed_list();
355 let mut components = Components::new_with_refreshed_list();
356 let mut users = Users::new_with_refreshed_list();
357
358 println!("Done.");
359 let t_stin = io::stdin();
360 let mut stin = t_stin.lock();
361 let mut done = false;
362
363 println!("To get the commands' list, enter 'help'.");
364 while !done {
365 let mut input = String::new();
366 write!(&mut io::stdout(), "> ");
367 io::stdout().flush();
368
369 stin.read_line(&mut input);
370 if input.is_empty() {
371 // The string is empty, meaning there is no '\n', meaning
372 // that the user used CTRL+D so we can just quit!
373 println!("\nLeaving, bye!");
374 break;
375 }
376 if (&input as &str).ends_with('\n') {
377 input.pop();
378 }
379 done = interpret_input(
380 input.as_ref(),
381 &mut system,
382 &mut networks,
383 &mut disks,
384 &mut components,
385 &mut users,
386 );
387 }
388}Sourcepub fn list(&self) -> &HashMap<String, NetworkData>
pub fn list(&self) -> &HashMap<String, NetworkData>
Returns the network interfaces map.
use sysinfo::Networks;
let networks = Networks::new_with_refreshed_list();
for network in networks.list() {
println!("{network:?}");
}Sourcepub fn refresh(&mut self, remove_not_listed_interfaces: bool)
pub fn refresh(&mut self, remove_not_listed_interfaces: bool)
Refreshes the network interfaces.
use sysinfo::Networks;
let mut networks = Networks::new_with_refreshed_list();
// Wait some time...? Then refresh the data of each network.
networks.refresh(true);Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}Methods from Deref<Target = HashMap<String, NetworkData>>§
1.0.0pub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
This number is a lower bound; the HashMap<K, V> might be able to hold
more, but is guaranteed to be able to hold at least this many.
§Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);1.0.0pub fn keys(&self) -> Keys<'_, K, V>
pub fn keys(&self) -> Keys<'_, K, V>
An iterator visiting all keys in arbitrary order.
The iterator element type is &'a K.
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for key in map.keys() {
println!("{key}");
}§Performance
In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0pub fn values(&self) -> Values<'_, K, V>
pub fn values(&self) -> Values<'_, K, V>
An iterator visiting all values in arbitrary order.
The iterator element type is &'a V.
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values() {
println!("{val}");
}§Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0pub fn iter(&self) -> Iter<'_, K, V>
pub fn iter(&self) -> Iter<'_, K, V>
An iterator visiting all key-value pairs in arbitrary order.
The iterator element type is (&'a K, &'a V).
§Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for (key, val) in map.iter() {
println!("key: {key} val: {val}");
}§Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
Examples found in repository?
70fn interpret_input(
71 input: &str,
72 sys: &mut System,
73 networks: &mut Networks,
74 disks: &mut Disks,
75 components: &mut Components,
76 users: &mut Users,
77) -> bool {
78 match input.trim() {
79 "help" => print_help(),
80 "refresh_disks" => {
81 println!("Refreshing disk list...");
82 disks.refresh(true);
83 println!("Done.");
84 }
85 "refresh_users" => {
86 println!("Refreshing user list...");
87 users.refresh();
88 println!("Done.");
89 }
90 "refresh_networks" => {
91 println!("Refreshing network list...");
92 networks.refresh(true);
93 println!("Done.");
94 }
95 "refresh_components" => {
96 println!("Refreshing component list...");
97 components.refresh(true);
98 println!("Done.");
99 }
100 "refresh_cpu" => {
101 println!("Refreshing CPUs...");
102 sys.refresh_cpu_all();
103 println!("Done.");
104 }
105 "signals" => {
106 for (nb, sig) in SUPPORTED_SIGNALS.iter().enumerate() {
107 println!("{:2}:{sig:?}", nb + 1);
108 }
109 }
110 "cpus" => {
111 // Note: you should refresh a few times before using this, so that usage statistics
112 // can be ascertained
113 println!(
114 "number of physical cores: {}",
115 System::physical_core_count()
116 .map(|c| c.to_string())
117 .unwrap_or_else(|| "Unknown".to_owned()),
118 );
119 println!("total CPU usage: {}%", sys.global_cpu_usage());
120 for cpu in sys.cpus() {
121 println!("{cpu:?}");
122 }
123 }
124 "memory" => {
125 println!("total memory: {: >10} KB", sys.total_memory() / 1_000);
126 println!(
127 "available memory: {: >10} KB",
128 sys.available_memory() / 1_000
129 );
130 println!("used memory: {: >10} KB", sys.used_memory() / 1_000);
131 println!("total swap: {: >10} KB", sys.total_swap() / 1_000);
132 println!("used swap: {: >10} KB", sys.used_swap() / 1_000);
133 }
134 "quit" | "exit" => return true,
135 "all" => {
136 for (pid, proc_) in sys.processes() {
137 println!(
138 "{}:{} status={:?}",
139 pid,
140 proc_.name().to_string_lossy(),
141 proc_.status()
142 );
143 }
144 }
145 "frequency" => {
146 for cpu in sys.cpus() {
147 println!("[{}] {} MHz", cpu.name(), cpu.frequency());
148 }
149 }
150 "vendor_id" => {
151 println!("vendor ID: {}", sys.cpus()[0].vendor_id());
152 }
153 "brand" => {
154 println!("brand: {}", sys.cpus()[0].brand());
155 }
156 "load_avg" => {
157 let load_avg = System::load_average();
158 println!("one minute : {}%", load_avg.one);
159 println!("five minutes : {}%", load_avg.five);
160 println!("fifteen minutes: {}%", load_avg.fifteen);
161 }
162 e if e.starts_with("show ") => {
163 let tmp: Vec<&str> = e.split(' ').filter(|s| !s.is_empty()).collect();
164
165 if tmp.len() != 2 {
166 println!("show command takes a pid or a name in parameter!");
167 println!("example: show 1254");
168 } else if let Ok(pid) = Pid::from_str(tmp[1]) {
169 match sys.process(pid) {
170 Some(p) => {
171 println!("{:?}", *p);
172 println!(
173 "Files open/limit: {:?}/{:?}",
174 p.open_files(),
175 p.open_files_limit(),
176 );
177 }
178 None => {
179 println!("pid \"{pid:?}\" not found");
180 }
181 }
182 } else {
183 let proc_name = tmp[1];
184 for proc_ in sys.processes_by_name(proc_name.as_ref()) {
185 println!("==== {} ====", proc_.name().to_string_lossy());
186 println!("{proc_:?}");
187 }
188 }
189 }
190 "temperature" => {
191 for component in components.iter() {
192 println!("{component:?}");
193 }
194 }
195 "network" => {
196 for (interface_name, data) in networks.iter() {
197 println!(
198 "\
199{interface_name}:
200 ether {}
201 input data (new / total): {} / {} B
202 output data (new / total): {} / {} B",
203 data.mac_address(),
204 data.received(),
205 data.total_received(),
206 data.transmitted(),
207 data.total_transmitted(),
208 );
209 }
210 }
211 "show" => {
212 println!("'show' command expects a pid number or a process name");
213 }
214 e if e.starts_with("kill ") => {
215 let tmp: Vec<&str> = e
216 .split(' ')
217 .map(|s| s.trim())
218 .filter(|s| !s.is_empty())
219 .collect();
220
221 if tmp.len() != 3 {
222 println!("kill command takes the pid and a signal number in parameter!");
223 println!("example: kill 1254 9");
224 } else {
225 let Ok(pid) = Pid::from_str(tmp[1]) else {
226 eprintln!("Expected a number for the PID, found {:?}", tmp[1]);
227 return false;
228 };
229 let Ok(signal) = usize::from_str(tmp[2]) else {
230 eprintln!("Expected a number for the signal, found {:?}", tmp[2]);
231 return false;
232 };
233 let Some(signal) = SUPPORTED_SIGNALS.get(signal) else {
234 eprintln!(
235 "No signal matching {signal}. Use the `signals` command to get the \
236 list of signals.",
237 );
238 return false;
239 };
240
241 match sys.process(pid) {
242 Some(p) => {
243 if let Some(res) = p.kill_with(*signal) {
244 println!("kill: {res}");
245 } else {
246 eprintln!("kill: signal not supported on this platform");
247 }
248 }
249 None => {
250 eprintln!("pid not found");
251 }
252 }
253 }
254 }
255 "disks" => {
256 for disk in disks {
257 println!("{disk:?}");
258 }
259 }
260 "users" => {
261 for user in users {
262 println!("{:?} => {:?}", user.name(), user.groups());
263 }
264 }
265 "groups" => {
266 for group in Groups::new_with_refreshed_list().list() {
267 println!("{group:?}");
268 }
269 }
270 "boot_time" => {
271 println!("{} seconds", System::boot_time());
272 }
273 "uptime" => {
274 let up = System::uptime();
275 let mut uptime = up;
276 let days = uptime / 86400;
277 uptime -= days * 86400;
278 let hours = uptime / 3600;
279 uptime -= hours * 3600;
280 let minutes = uptime / 60;
281 println!("{days} days {hours} hours {minutes} minutes ({up} seconds in total)");
282 }
283 x if x.starts_with("refresh") => {
284 if x == "refresh" {
285 println!("Getting processes' information...");
286 sys.refresh_all();
287 println!("Done.");
288 } else if x.starts_with("refresh ") {
289 println!("Getting process' information...");
290 if let Some(pid) = x
291 .split(' ')
292 .filter_map(|pid| pid.parse().ok())
293 .take(1)
294 .next()
295 {
296 if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
297 println!("Process `{pid}` updated successfully");
298 } else {
299 println!("Process `{pid}` couldn't be updated...");
300 }
301 } else {
302 println!("Invalid [pid] received...");
303 }
304 } else {
305 println!(
306 "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
307 list.",
308 );
309 }
310 }
311 "pid" => {
312 println!(
313 "PID: {}",
314 sysinfo::get_current_pid().expect("failed to get PID")
315 );
316 }
317 "system" => {
318 println!(
319 "System name: {}\n\
320 System kernel version: {}\n\
321 System OS version: {}\n\
322 System OS (long) version: {}\n\
323 System host name: {}\n\
324 System kernel: {}",
325 System::name().unwrap_or_else(|| "<unknown>".to_owned()),
326 System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
327 System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
328 System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
329 System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
330 System::kernel_long_version(),
331 );
332 }
333 "motherboard" => match Motherboard::new() {
334 Some(m) => println!("{m:#?}"),
335 None => println!("No motherboard information available"),
336 },
337 "product" => {
338 println!("{:#?}", Product);
339 }
340 e => {
341 println!(
342 "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
343 list.",
344 );
345 }
346 }
347 false
348}1.0.0pub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);1.0.0pub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the map contains no elements.
§Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());1.9.0pub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the map’s [BuildHasher].
§Examples
use std::collections::HashMap;
use std::hash::RandomState;
let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();1.0.0pub fn get<Q>(&self, k: &Q) -> Option<&V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn get<Q>(&self, k: &Q) -> Option<&V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
[Hash] and [Eq] on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);1.40.0pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns the key-value pair corresponding to the supplied key. This is potentially useful:
- for key types where non-identical keys can be considered equal;
- for getting the
&Kstored key value from a borrowed&Qlookup key; or - for getting a reference to a key with the same lifetime as the collection.
The supplied key may be any borrowed form of the map’s key type, but
[Hash] and [Eq] on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Debug)]
struct S {
id: u32,
name: &'static str, // ignored by equality and hashing operations
}
impl PartialEq for S {
fn eq(&self, other: &S) -> bool {
self.id == other.id
}
}
impl Eq for S {}
impl Hash for S {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);
let mut map = HashMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);1.0.0pub fn contains_key<Q>(&self, k: &Q) -> boolwhere
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn contains_key<Q>(&self, k: &Q) -> boolwhere
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns true if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but
[Hash] and [Eq] on the borrowed form must match those for
the key type.
§Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);