HashMap<K, V>
7 methods使用二次探测和 SipHash 1-3(或 2-4)哈希实现的哈希映射。
String::new() -> String创建一个空的 HashMap,使用默认哈希器和容量。
Returns
String
Example
rust
let s = String::new();
assert!(s.is_empty());String::from(s: &str) -> String插入一个键值对。如果键已存在,则返回旧值。
Parameters
| Name | Type | Description |
|---|---|---|
| s | &str | 要插入的键。 |
Returns
String
Example
rust
let s = String::from("hello");
assert_eq!(s, "hello");s.push_str(s2: &str)返回与键对应的值的引用。
Parameters
| Name | Type | Description |
|---|---|---|
| s2 | &str | 要查找的键。 |
Returns
()
Example
rust
let mut s = String::from("foo");
s.push_str("bar");
assert_eq!(s, "foobar");s.push(ch: char)从映射中移除一个键,如果键之前存在于映射中则返回该键对应的值。
Parameters
| Name | Type | Description |
|---|---|---|
| ch | char | 要移除的键。 |
Returns
()
Example
rust
let mut s = String::from("abc");
s.push('1');
s.push('2');
assert_eq!(s, "abc12");s.len() -> usize返回映射中元素的数量。
Returns
usize
Example
rust
let s = String::from("hello");
assert_eq!(s.len(), 5);
let nihongo = String::from("日本語");
assert_eq!(nihongo.len(), 9); // 3 chars * 3 bytess.as_str() -> &str如果映射包含指定键的值,则返回 true。
Returns
&str
Example
rust
let s = String::from("hello");
let slice: &str = s.as_str();
assert_eq!(slice, "hello");s.replace(from: &str, to: &str) -> String返回一个以任意顺序访问所有键值对的迭代器。
Parameters
| Name | Type | Description |
|---|---|---|
| from | &str | Pattern to replace. |
| to | &str | Replacement string. |
Returns
String
Example
rust
let s = String::from("this is old");
assert_eq!(s.replace("old", "new"), "this is new");