Hash_Table module

find_or_add

procedure · 1 overloadSource

Finds the value for key, adding a zero-initialized one if there is none. Returns a pointer to it and whether it was just added.

This is the way to update a value that may not exist yet with a single lookup.

ExampleOpen in playground ↗
counts: Table(string, int);
for word: string.["a", "b", "a"] {
    count, added := find_or_add(*counts, word);
    count.* += 1;
}
assert(table_find_pointer(*counts, "a").* == 2 && counts.count == 2);
deinit(*counts);
find_or_add :: (
    table: *Table,
    key: table.Key_Type
) -> (entry: *table.Value_Type, newly_added: bool)

Finds the value for key, adding a zero-initialized one if there is none. Returns a pointer to it and whether it was just added.

This is the way to update a value that may not exist yet with a single lookup.

Parameters

table: *Table
key: table.Key_Type

Returns

entry: *table.Value_Type
newly_added: bool
ExampleOpen in playground ↗
counts: Table(string, int);
for word: string.["a", "b", "a"] {
    count, added := find_or_add(*counts, word);
    count.* += 1;
}
assert(table_find_pointer(*counts, "a").* == 2 && counts.count == 2);
deinit(*counts);

See also