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()- whetherTis a Mojo struct type.field_count()- number of fields.field_names()-InlineArray[StaticString, N]of field names.field_types()- aTypeListof field types.field_index[name]()- index of the named field.field_type[name]()- aReflected[FieldT]handle for the named field's type.field_offset[name=...]()/field_offset[index=...]()- byte offset.field_ref[idx](s)- reference to field at indexidxin values.
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 Float64Structsβ
- β
Reflected: A compile-time reflection handle for a type.
Functionsβ
- β
reflect: Returns a compile-time reflection handle for typeT.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!