Map
Native methods and properties
| Member | Signature | Behavior |
|---|---|---|
size | usize | Number of key-value pairs. |
set | set(key: K, value: V): Map<K, V> | Inserts or replaces a value for a key and returns the map. |
get | get(key: K): V? | Returns the value, or absence when the key is missing. |
getOrInsert | getOrInsert(key: K, fallback: V): V | Returns a mutable reference to the stored value, inserting the fallback only when the key is missing. |
has | has(key: K): boolean | Checks whether a key is present. |
delete | delete(key: K): boolean | Removes a key and reports whether it was present. |
keys | keys(): K[] | Returns the keys as an array. |
values | values(): V[] | Returns the values as an array. |
entries | entries(): [K, V][] | Returns key-value pairs as an array; it can also be traversed with for...of. |
Map
tyrus
interface User {
name: string;
email: string;
}
const users: Map<i32, User> = Map<i32, User>();
users.set(1, { name: "Ada", email: "[email protected]" });
users.set(2, { name: "Grace", email: "[email protected]" });
const first: User? = users.get(1);
print(first?.name ?? "unknown"); // "Ada"
const exists: boolean = users.has(2); // true
const size: usize = users.size; // 2
for (const [id, user] of users.entries()) {
print(`${id}: ${user.name}`);
// 1: Ada
// 2: Grace
}
const visits = users.getOrInsert(1, { name: "Ada", email: "[email protected]" });
// The fallback expression is evaluated only when key `1` is absent.getOrInsert(key, value) returns a mutable reference to the value for key. The fallback expression is lazy and runs only when the key is absent.
