Mojo module
struct_fields
Provides struct field reflection and introspection utilities.
This module provides compile-time introspection of struct fields:
struct_field_count[T]()- returns the number of fieldsstruct_field_names[T]()- returns anInlineArray[StaticString, N]of field namesstruct_field_types[T]()- returns a variadic of field types
These APIs work with both concrete types and generic type parameters, enabling generic serialization, comparison, and other reflection-based utilities.
For field lookup by name (concrete types only):
struct_field_index_by_name[T, name]()- returns the index of a field by namestruct_field_type_by_name[T, name]()- returns the type of a field by name
Example iterating over all fields (works with generics):
fn print_fields[T: AnyType]():
comptime names = struct_field_names[T]()
@parameter
for i in range(struct_field_count[T]()):
print(names[i])
fn main():
print_fields[Point]() # Works with any struct!Example looking up a field by name:
comptime idx = struct_field_index_by_name[Point, "x"]() # 0
comptime field_type = struct_field_type_by_name[Point, "y"]()
var value: field_type.T = 3.14 # field_type.T is Float64For accessing struct field values by index (returns a reference, not a copy):
__struct_field_ref(idx, ref s)- returns a reference to the field at index
The __struct_field_ref magic function enables reflection-based utilities to work
with non-copyable types by returning references instead of copies. It works with
both literal indices and parametric indices (such as loop variables in
@parameter for loops):
struct Container:
var id: Int
var resource: NonCopyableResource
fn inspect(ref c: Container):
# Get references to fields without copying
ref id_ref = __struct_field_ref(0, c)
ref resource_ref = __struct_field_ref(1, c)
print("id:", id_ref)
print("resource:", resource_ref.data)
# Mutation through reference also works
__struct_field_ref(0, c) = 42
# Works in generic contexts with parameter indices
fn print_all_fields[T: AnyType](ref s: T):
comptime names = struct_field_names[T]()
@parameter
for i in range(struct_field_count[T]()):
print(names[i], "=", __struct_field_ref(i, s))Structs
-
ReflectedType: Wrapper struct for compile-time type values from reflection.
Functions
-
is_struct_type: ReturnsTrueifTis a Mojo struct type,Falseotherwise. -
struct_field_count: Returns the number of fields in structT. -
struct_field_index_by_name: Returns the index of the field with the given name in structT. -
struct_field_names: Returns the names of all fields in structTas an InlineArray. -
struct_field_type_by_name: Returns the type of the field with the given name in structStructT. -
struct_field_types: Returns the types of all fields in structTas a variadic.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!