Skip to main content

Mojo function

struct_field_count

struct_field_count[T: AnyType]() -> Int

Returns the number of fields in struct T.

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

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

Example:

fn count_fields[T: AnyType]() -> Int:
    return struct_field_count[T]()

fn main():
    print(count_fields[MyStruct]())  # Prints field count

Constraints:

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

Parameters:

Returns:

Int: The number of fields in the struct.

Was this page helpful?