Mojo function
offset_of
offset_of[T: AnyType, *, name: StringLiteral[value], target: __mlir_type.!kgen.target = _current_target()]() -> Int
Returns the byte offset of a field within a struct by name.
This function computes the byte offset from the start of the struct to the named field, accounting for alignment padding between fields. The offset is computed using the target's data layout.
This is useful for low-level memory operations like no-copy serialization, memory-mapped I/O, or interfacing with C structs.
Note: This function works with both concrete types and generic type parameters.
Example:
struct Point:
var x: Int # offset 0
var y: Float64 # offset 8 (aligned to 8 bytes)
fn main():
comptime x_off = offset_of[Point, name="x"]() # 0
comptime y_off = offset_of[Point, name="y"]() # 8Constraints:
T must be a struct type. The field name must exist in the struct.
Parameters:
- T (
AnyType): A struct type. - name (
StringLiteral): The name of the field. - target (
__mlir_type.!kgen.target``): The target architecture (defaults to current target).
Returns:
Int: The byte offset of the field from the start of the struct.
offset_of[T: AnyType, *, index: Int, target: __mlir_type.!kgen.target = _current_target()]() -> Int
Returns the byte offset of a field within a struct by index.
This function computes the byte offset from the start of the struct to the specified field, accounting for alignment padding between fields. The offset is computed using the target's data layout.
This is useful for low-level memory operations like no-copy serialization, memory-mapped I/O, or interfacing with C structs.
Note: This function works with both concrete types and generic type parameters.
Example:
struct Point:
var x: Int # offset 0
var y: Float64 # offset 8 (aligned to 8 bytes)
fn main():
comptime x_off = offset_of[Point, index=0]() # 0
comptime y_off = offset_of[Point, index=1]() # 8Constraints:
T must be a struct type. The index must be valid (0 <= index < field_count).
Parameters:
- T (
AnyType): A struct type. - index (
Int): The zero-based index of the field. - target (
__mlir_type.!kgen.target``): The target architecture (defaults to current target).
Returns:
Int: The byte offset of the field from the start of the struct.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!