IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

TypeDict

struct TypeDict[T: Equatable & Movable, Trait: AnyTrait[AnyType], //, keys: List[T], *values: Trait]

A compile-time map from a value of type T to a type.

TypeDict pairs a list of compile-time key values with a list of types of the same length. Looking up a key value yields the type at the matching position, so it acts as a value-keyed switch over types resolved entirely at compile time.

Examples:

from std.collections import TypeDict
from std.testing import assert_equal

comptime td = TypeDict[
T=Int,
Trait=AnyType,
[1,2,3],
Int, String, Float64,
]

def main() raises:
comptime assert td.get[1] == Int
comptime assert td.get[2] == String
comptime assert td.get[3] == Float64
assert_equal(td.length, 3)

Parameters

  • T (Equatable & Movable): The type of the key values.
  • Trait (AnyTrait[AnyType]): The trait that every mapped type conforms to.
  • keys (List[T]): The key values, one per mapped type.
  • *values (Trait): The mapped types, parallel to keys.

Implemented traits

AnyType, Copyable, ImplicitlyCopyable, ImplicitlyDeletable, Movable, RegisterPassable, TrivialRegisterPassable

comptime members

get

comptime get[key: T] = values[SIMDLength(keys.try_index(key, Int(0), Optional(None)).or_else(TypeDict._assert_key_is_present[key]()))]

Gets the type mapped to key.

Constraints: key must be present in keys.

Parameters

  • key (T): The key value to look up.

length

comptime length = len[TypeList[values]](values)

The number of entries in the map.

Methods

__init__

def __init__() -> Self

Constructs a TypeDict.

Constraints:

keys and values must have the same length.

__len__

def __len__(self) -> Int

Gets the number of entries in the map.

Returns:

Int: The number of entries in the map (length).