Skip to main content

Mojo module

type_functions

Provides type functions for compile-time type manipulation.

Type functions are comptime declarations that produce a type from compile-time parameter inputs. Unlike regular fn functions which accept and return runtime values, type functions operate entirely at compile time -- they take comptime parameters and evaluate to a type, with no runtime component.

comptime values

ConditionalType

comptime ConditionalType[Trait: AnyTrait[AnyType], //, *, If: Bool, Then: Trait, Else: Trait] = #kgen.variadic.concat<#kgen.variadic<cond(#lit.struct.extract<:!lit.struct<@std::@builtin::@bool::@Bool> If, "_mlir_value">, [Then], []), [Else]> : !kgen.variadic<variadic<:!lit.anytrait<<@std::@builtin::@anytype::@AnyType>> Trait>>>[0]

A type function that conditionally selects between two types.

This type function evaluates a compile-time boolean condition and produces either type Then (if the condition is True) or type Else (if the condition is False). It is the type-level equivalent of the ternary conditional expression Then if If else Else.

Returns: Type Then if If is True, otherwise type Else.

Examples:

from utils.type_functions import ConditionalType
from sys import size_of

struct Wrapper[T: AnyType]:
    comptime StorageType = ConditionalType[
        Trait=ImplicitlyDestructible,
        If=size_of[Self.T]() > 0,
        Then=List[Byte],
        Else=NoneType,
    ]

    var storage: Self.StorageType

Parameters

  • Trait (AnyTrait): A trait that both Then and Else must conform to.
  • If (Bool): A compile-time boolean that determines which type to select.
  • Then (Trait): The type to produce if the condition is True.
  • Else (Trait): The type to produce if the condition is False.

Was this page helpful?