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).

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.

reflect is auto-imported via the prelude, so it is available without an explicit import. Reflected[T] must be imported from std.reflection when named in signatures.

Example:

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

  • Reflected: A compile-time reflection handle for a type.

Functions

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