Skip to main content

Mojo function

struct_field_types

struct_field_types[T: AnyType]() -> Variadic[AnyTrivialRegType]

Returns the types of all fields in struct T as a variadic.

This function works with both concrete types and generic type parameters.

For nested structs, this returns the struct type itself, not its flattened fields. Use recursive calls to introspect nested types.

Note: For best performance, assign the result to a comptime variable to ensure compile-time evaluation: comptime types = struct_field_types[T]()

Example:

fn print_field_types[T: AnyType]():
    comptime types = struct_field_types[T]()
    @parameter
    for i in range(struct_field_count[T]()):
        print(get_type_name[types[i]]())

fn main():
    print_field_types[MyStruct]()  # Works with any struct!

Constraints:

T must be a struct type. Passing a non-struct type results in a compile-time error.

Parameters:

Returns:

Variadic: A variadic of types, one for each field in the struct. Access individual types by indexing: types[i].

Was this page helpful?