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.

reflect[T] is a comptime alias for the Reflected[T] handle type, which exposes type introspection through static methods. The handle has no runtime state — T is carried entirely in the compile-time parameter — so all queries are spelled as reflect[T].method() (no parens after [T]).

  • 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] - Reflected[FieldT] 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 names = reflect[T].field_names()
comptime for i in range(reflect[T].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 directly:

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

comptime values

reflect

comptime reflect[T: AnyType] = Reflected[T]

A compile-time alias for the reflection handle type of T.

Resolves to Reflected[T], whose static methods expose introspection of T. Use it as reflect[T].method() rather than constructing an instance.

reflect is auto-imported via the prelude.

Example:

struct Point:
var x: Int
var y: Float64

def main():
print(reflect[Point].field_count()) # 2

Parameters

  • T (AnyType): The type to introspect.

Structs

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