Dictionaries
| Item | Summary |
|---|---|
get | Returns the value stored under key, or null if there isn’t one |
get_or_insert | Returns the entry under the key |
len | Returns the number of entries |
contains_key | Returns whether the dictionary has an entry for key |
insert | Sets key to value and returns the value it replaced, or null if the key is new |
remove | Removes the entry for key and returns its value, or returns null if there was no such entry |
pairs | Returns every entry as a (key, value) tuple, in the order the keys were first inserted |
Methods
get
fn get(self, key: str) -> T?
Returns the value stored under key, or null if there isn’t one. This is the same as
indexing with dict[key].
let ages = ~{ ada = 36 };
let a = ages.get("ada"); // 36
let b = ages.get("bob"); // null
get_or_insert
fn get_or_insert(self, key: str, default: T) -> T
Returns the entry under the key. If none is found, default is inserted at key and is
returned instead.
let ages = ~{ ada = 36 };
let a = ages.get("ada"); // 36
let b = ages.get_or_insert("bob", 28); // 28
len
fn len(self) -> int
Returns the number of entries.
let n = ~{ a = 1, b = 2 }.len(); // 2
contains_key
fn contains_key(self, key: str) -> bool
Returns whether the dictionary has an entry for key. Unlike indexing, this tells a missing
key apart from one whose value is null.
let slots: ~{int?} = ~{ a = null };
let a = slots.contains_key("a"); // true, though slots["a"] is null
let b = slots.contains_key("b"); // false
insert
fn insert(self, key: str, value: T) -> T?
Sets key to value and returns the value it replaced, or null if the key is new. A new key
is added at the end of the iteration order. Replacing a value doesn’t move its key.
Assigning with dict[key] = value does the same without returning anything.
let stock = ~{ apples = 3 };
let old = stock.insert("apples", 5); // 3
let new = stock.insert("pears", 2); // null
remove
fn remove(self, key: str) -> T?
Removes the entry for key and returns its value, or returns null if there was no such
entry. The remaining entries keep their order.
let stock = ~{ apples = 3, pears = 2 };
let a = stock.remove("apples"); // 3, and stock is now ~{ pears = 2 }
let b = stock.remove("plums"); // null
pairs
fn pairs(self) -> [(str, T)]
Returns every entry as a (key, value) tuple, in the order the keys were first inserted.
let scores = ~{ ada = 3, bob = 5 };
let entries = scores.pairs(); // [("ada", 3), ("bob", 5)]
A for loop over the dictionary visits the same pairs without building an array:
for (name, score) in scores {
print(f"{name} has {score}");
}