Mojo function
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:
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.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!