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: 1.0
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).

struct_field_ref

struct_field_ref[idx: Int, T: AnyType](ref s: T) -> ref[s] #kgen.struct_field_types<:trait<_std::_builtin::_anytype::_AnyType> T>[idx]

Deprecated: use reflect[T]().field_ref[idx](s) instead.

Returns a reference to the struct field at the given index.

This function provides reference-based access to struct fields by index, enabling 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 comptime for loops), and with both concrete struct types and generic type parameters.

Example:

from std.reflection import struct_field_ref

@fieldwise_init
struct Container:
var id: Int
var name: String

def inspect(mut c: Container):
ref id_ref = struct_field_ref[0](c)
ref name_ref = struct_field_ref[1](c)

# Mutation through reference
struct_field_ref[0](c) = 42

def main():
var c = Container(id=1, name="test")
inspect(c)

Deprecated: Use reflect[T]().field_ref[idx](s) instead.

Constraints:

T must be a struct type. The index must be in range [0, struct_field_count[T]()).

Parameters:

  • idx (Int): The zero-based index of the field.
  • T (AnyType): A struct type.

Args:

  • s (T): The struct value to access.

Returns:

ref[s] #kgen.struct_field_types<:trait<_std::_builtin::_anytype::_AnyType> T>[idx]: A reference to the field at the specified index, with the same mutability as s.