Skip to main content

Mojo module

reflect

Provides the unified reflect[T] / Reflected[T] reflection API.

This module exposes a single entry point reflect[T]() which returns a Reflected[T] handle. The handle exposes struct introspection through methods, without the struct_ prefix used by the legacy free-function API:

  • is_struct() - whether T is a Mojo struct type.
  • field_count() - number of fields.
  • field_names() - InlineArray[StaticString, N] of field names.
  • field_types() - a TypeList of field types.
  • field_index[name]() - index of the named field.
  • field_type[name]() - a Reflected[FieldT] handle for the named field's type.
  • field_offset[name=...]() / field_offset[index=...]() - byte offset.
  • field_ref[idx](s) - reference to field at index idx in value s.

Example:

from std.reflection import reflect

struct Point:
    var x: Int
    var y: Float64

def print_fields[T: AnyType]():
    comptime r = reflect[T]()
    comptime names = r.field_names()
    comptime for i in range(r.field_count()):
        print(names[i])

def main():
    print_fields[Point]()

The wrapped type is exposed as the T parameter, so the result of field_type[name]() can be used as a type:

def main():
    comptime r = reflect[Point]()
    comptime y_type = r.field_type["y"]()
    var v: y_type.T = 3.14  # y_type.T is Float64

Structs​

Functions​

  • ​reflect: Returns a compile-time reflection handle for type T.

Was this page helpful?