@FieldType Semantics #35826

Open
opened 2026-06-18 02:22:51 +02:00 by MasonRemaley · 5 comments
Owner

Zig Version

0.17.0-dev.831+431092fa6

Steps to Reproduce, Observed Behavior, and Expected Behavior

@FieldType Semantics

Current Semantics

The section of the manual on @FieldType says:

Given a type and the name of one of its fields, returns the type of that field. 

However, the current implementation supports some additional usages not described here. I believe this is an unintentional consequence of @FieldType being built on top of an existing internal feature:

const MyStruct = struct { my_field: u32 };
comptime assert(@FieldType(?MyStruct, "my_field") == u32); // unexpectedly compiles & passes
comptime assert(@FieldType(anyerror!MyStruct, "my_field") == u32); // unexpectedly compiles & passes

Additionally, @FieldType doesn't support some usages you might expect it to. I suspect that these omissions weren't intentional, but I could be mistaken:

const array: [2]u32 = @splat(0);
const slice: []const u32 = &array;

comptime assert(@field(array, "len") == 2); // passes
comptime assert(@field(slice, "len") == 2); // passes
comptime assert(@field(slice, "ptr") == slice.ptr); // passes

comptime assert(@FieldType(@TypeOf([2]u32), "len") == usize); // error: expected struct or union; found '[2]u32'
comptime assert(@FieldType(@TypeOf([]const u32), "len") == usize); // error: expected struct or union; found '[]const u32'
comptime assert(@FieldType(@TypeOf([]const u32), "ptr") == [*]const u32); // error: expected struct or union; found '[]const u32'

Should @FieldType be 1:1 with @field?

It's tempting to suggest that @FieldType(foo, "bar") should always be equivalent to @TypeOf(@field(foo, "bar")). However, that would require @FieldType to support operating on pointers, which currently does not:

const my_struct: *const MyStruct = &.{ .my_field = 0 };
comptime assert(@field(my_struct, "my_field") == 0);
comptime assert(@FieldType(*const MyStruct, "my_field") == 0); // error: expected struct or union; found '*const main.main.MyStruct'

It makes sense that @field supports this since it's supposed to mimic the . operator.

It would seem odd to me for @FieldType to support operating on pointers, but I don't have a strong argument as to why and could see the value in these being 1:1, so I'm open to having my mind changed.

Pointers To Fields

@field has one additional trick up its sleeve that @FieldType doesn't: you can take the address of the result of @field.

On the flip side, it's not currently possible to reconstruct the type of a pointer to a field using just @FieldType.

A naive attempt would be *@FieldType(MyStruct, "my_field"), but this drops all the pointer attributes.

You could manually reify a new pointer type to add them back, but this would still fail if it was a pointer into a packed struct. Not only is it not currently possile to reify bit pointers, even if it was, short of reimplementing part of the compiler in comptime using reflection info you wouldn't know what offset and byte size to use.

Currently your best try (assuming you don't have an actual pointer to the parent) is to create a dummy parent pointer:


fn FieldPtr(comptime ParentPtr: type, comptime field_name: []const u8) type {
    const ptr_info = @typeInfo(ParentPtr).pointer;
    const ptr_align = ptr_info.attrs.@"align" orelse @alignOf(ptr_info.child);
    const parent_ptr: ParentPtr = @ptrFromInt(ptr_align);
    return @TypeOf(&@field(parent_ptr, field_name));
}

Note to mlugg: I think we concluded this doesn't work yesterday due to an issue relating to alignment. I plugged it back into my use case just now to remind myself why exactly it doesn't work, and, well, it works. I suspect that I either misremember this part of our conversation and it was an earlier try, or we were lead astray by my half finished refactor.

Proposal

I'm interested in others feedback on this topic before making a concrete proposal. Here are my thoughts so far:

  • We either need to remove the extra optional/error set functionality from @FieldType or document that it exists. I believe it's unintentional and should be removed.
  • I am undecided on whether @FieldType should operate on pointers the way @field does. Having @FieldType and @field be 1:1 could provide utility, but having @FieldType operate on pointers seems odd.
  • We should consider either adding the example FieldPtr implementation to the standard library, or adding a builtin that achieves the same thing.

CC @jacobly @mlugg

### Zig Version 0.17.0-dev.831+431092fa6 ### Steps to Reproduce, Observed Behavior, and Expected Behavior # `@FieldType` Semantics ## Current Semantics The section of the manual on `@FieldType` says: ``` Given a type and the name of one of its fields, returns the type of that field. ``` However, the current implementation supports some additional usages not described here. I believe this is an unintentional consequence of `@FieldType` being built on top of an existing internal feature: ```zig const MyStruct = struct { my_field: u32 }; comptime assert(@FieldType(?MyStruct, "my_field") == u32); // unexpectedly compiles & passes comptime assert(@FieldType(anyerror!MyStruct, "my_field") == u32); // unexpectedly compiles & passes ``` Additionally, `@FieldType` doesn't support some usages you might expect it to. I suspect that these omissions weren't intentional, but I could be mistaken: ```zig const array: [2]u32 = @splat(0); const slice: []const u32 = &array; comptime assert(@field(array, "len") == 2); // passes comptime assert(@field(slice, "len") == 2); // passes comptime assert(@field(slice, "ptr") == slice.ptr); // passes comptime assert(@FieldType(@TypeOf([2]u32), "len") == usize); // error: expected struct or union; found '[2]u32' comptime assert(@FieldType(@TypeOf([]const u32), "len") == usize); // error: expected struct or union; found '[]const u32' comptime assert(@FieldType(@TypeOf([]const u32), "ptr") == [*]const u32); // error: expected struct or union; found '[]const u32' ``` ## Should `@FieldType` be 1:1 with `@field`? It's tempting to suggest that `@FieldType(foo, "bar")` should always be equivalent to `@TypeOf(@field(foo, "bar"))`. However, that would require `@FieldType` to support operating on pointers, which currently does not: ```zig const my_struct: *const MyStruct = &.{ .my_field = 0 }; comptime assert(@field(my_struct, "my_field") == 0); comptime assert(@FieldType(*const MyStruct, "my_field") == 0); // error: expected struct or union; found '*const main.main.MyStruct' ``` It makes sense that `@field` supports this since it's supposed to mimic the `.` operator. It would seem odd to me for `@FieldType` to support operating on pointers, but I don't have a strong argument as to why and could see the value in these being 1:1, so I'm open to having my mind changed. ## Pointers To Fields `@field` has one additional trick up its sleeve that `@FieldType` doesn't: you can take the address of the result of `@field`. On the flip side, it's not currently possible to reconstruct the type of a pointer to a field using just `@FieldType`. A naive attempt would be `*@FieldType(MyStruct, "my_field")`, but this drops all the pointer attributes. You could manually reify a new pointer type to add them back, but this would still fail if it was a pointer into a packed struct. Not only is it not currently possile to reify bit pointers, even if it was, short of reimplementing part of the compiler in comptime using reflection info you wouldn't know what offset and byte size to use. Currently your best try (assuming you don't have an actual pointer to the parent) is to create a dummy parent pointer: ```zig fn FieldPtr(comptime ParentPtr: type, comptime field_name: []const u8) type { const ptr_info = @typeInfo(ParentPtr).pointer; const ptr_align = ptr_info.attrs.@"align" orelse @alignOf(ptr_info.child); const parent_ptr: ParentPtr = @ptrFromInt(ptr_align); return @TypeOf(&@field(parent_ptr, field_name)); } ``` *Note to mlugg: I think we concluded this doesn't work yesterday due to an issue relating to alignment. I plugged it back into my use case just now to remind myself why exactly it doesn't work, and, well, it works. I suspect that I either misremember this part of our conversation and it was an earlier try, or we were lead astray by my half finished refactor.* ## Proposal I'm interested in others feedback on this topic before making a concrete proposal. Here are my thoughts so far: * We either need to remove the extra optional/error set functionality from `@FieldType` or document that it exists. I believe it's unintentional and should be removed. * I am undecided on whether `@FieldType` should operate on pointers the way `@field` does. Having `@FieldType` and `@field` be 1:1 could provide utility, but having `@FieldType` operate on pointers seems odd. * We should consider either adding the example `FieldPtr` implementation to the standard library, or adding a builtin that achieves the same thing. *** CC @jacobly @mlugg
andrewrk added this to the Urgent milestone 2026-06-18 02:36:42 +02:00
Owner

Note to mlugg: I think we concluded this doesn't work yesterday due to an issue relating to alignment. I plugged it back into my use case just now to remind myself why exactly it doesn't work, and, well, it works. I suspect that I either misremember this part of our conversation and it was an earlier try, or we were lead astray by my half finished refactor.

This does work okay (I believe you're misremembering that part of the conversation), it's just kind of awkward and "feels" hacky, so I prefer to avoid it where possible :P

  • We either need to remove the extra optional/error set functionality from @FieldType or document that it exists. I believe it's unintentional and should be removed.

I agree---this behavior definitely seems accidental, to the extent that I think changing that is purely a bugfix rather than a proposal.

  • I am undecided on whether @FieldType should operate on pointers the way @field does. Having @FieldType and @field be 1:1 could provide utility, but having @FieldType operate on pointers seems odd.

It's unclear to me what the supposed utility is to having @field and @FieldType match in this way. To my mind, the answer to this question is straightforward: @FieldType should not support pointers, because there is no reason for it to do so. The main reason @field supports pointers is that it simplifies that builtin's definition to be precisely equivalent to the expression a.b. But @FieldType is not a substitute for any other expression, so it needs its own definition---and the simplest possible one is just "the type of the field with the given name on the given struct/union type".

(Using the more restrictive definition also means that if there actually does turn out to be a good use case, we can extend the builtin in the future without breakage, whereas changing the builtin in future to restrict its usage would be a breaking change.)

  • We should consider either adding the example FieldPtr implementation to the standard library, or adding a builtin that achieves the same thing.

I'd be down for having a builtin for this. However, I think this should be covered by a separate proposal (let's have this issue track the @FieldType behavior). I'll let you open a proposal or a Zulip thread to hash this out if you're interested, but just while I'm here, my initial thoughts are that I might suggest the following 3 builtins:

  • rename @FieldType to @Field
    • Rationale: if this is called @FieldType, the next one logically ought to be @FieldPtrType, which is a bit of a mouthful. The capitalization already disambiguates that it returns a type!
  • @FieldPtr(*struct { a: u32 }, "a") == *u32
  • @ElemPtr([]T) == *T
    • This might seem unnecessary and trivial to implement with metaprogramming, but it's a little more subtle than you might expect due to alignment---for instance, an element pointer of []align(1) u32 is *align(1) u32, but an element pointer of []align(8) u32 is *u32 (assuming @sizeOf(u32) == 4), because the stride between elements is only 4 bytes.
> *Note to mlugg: I think we concluded this doesn't work yesterday due to an issue relating to alignment. I plugged it back into my use case just now to remind myself why exactly it doesn't work, and, well, it works. I suspect that I either misremember this part of our conversation and it was an earlier try, or we were lead astray by my half finished refactor.* This *does* work okay (I believe you're misremembering that part of the conversation), it's just kind of awkward and "feels" hacky, so I prefer to avoid it where possible :P > * We either need to remove the extra optional/error set functionality from @FieldType or document that it exists. I believe it's unintentional and should be removed. I agree---this behavior definitely seems accidental, to the extent that I think changing that is purely a bugfix rather than a proposal. > * I am undecided on whether `@FieldType` should operate on pointers the way `@field` does. Having `@FieldType` and `@field` be 1:1 could provide utility, but having `@FieldType` operate on pointers seems odd. It's unclear to me what the supposed utility is to having `@field` and `@FieldType` match in this way. To my mind, the answer to this question is straightforward: `@FieldType` should not support pointers, because there is no reason for it to do so. The main reason `@field` supports pointers is that it simplifies that builtin's definition to be precisely equivalent to the expression `a.b`. But `@FieldType` is not a substitute for any other expression, so it needs its own definition---and the simplest possible one is just "the type of the field with the given name on the given struct/union type". (Using the more restrictive definition also means that if there actually *does* turn out to be a good use case, we can extend the builtin in the future without breakage, whereas changing the builtin in future to *restrict* its usage would be a breaking change.) > * We should consider either adding the example `FieldPtr` implementation to the standard library, or adding a builtin that achieves the same thing. I'd be down for having a builtin for this. However, I think this should be covered by a separate proposal (let's have this issue track the `@FieldType` behavior). I'll let you open a proposal or a Zulip thread to hash this out if you're interested, but just while I'm here, my initial thoughts are that I might suggest the following 3 builtins: * rename `@FieldType` to `@Field` * Rationale: if this is called `@FieldType`, the next one logically ought to be `@FieldPtrType`, which is a bit of a mouthful. The capitalization already disambiguates that it returns a type! * `@FieldPtr(*struct { a: u32 }, "a") == *u32` * `@ElemPtr([]T) == *T` * This might seem unnecessary and trivial to implement with metaprogramming, but it's a little more subtle than you might expect due to alignment---for instance, an element pointer of `[]align(1) u32` is `*align(1) u32`, but an element pointer of `[]align(8) u32` is `*u32` (assuming `@sizeOf(u32) == 4`), because the stride between elements is only 4 bytes.

for instance, an element pointer of []align(1) u32 is *align(1) u32, but an element pointer of []align(8) u32 is []u32 (assuming @sizeOf(u32) == 4), because the stride between elements is only 4 bytes.

Don't you mean *u32 instead of []u32?

> for instance, an element pointer of `[]align(1) u32` is `*align(1) u32`, but an element pointer of `[]align(8) u32` is `[]u32` (assuming `@sizeOf(u32) == 4`), because the stride between elements is only 4 bytes. Don't you mean `*u32` instead of `[]u32`?
Owner

Yep, good catch, edited to fix.

Yep, good catch, edited to fix.

Hello,

It's seems that dropping alignment also affect @TypeOf and anytype, see below. Maybe const could be a thing to consider too. I guess if we address this issue, it will also address the issue of @FieldType.

I do not know if I should create a dedicated bug report.

fn require_align_8(x: *const align(8) u8) void { _ = x; }

fn generic_8(x : anytype) void {
    require_align_8(&x);
}
test "001" {
    // TypeOf Drop alignment
    const v0: u8 align(8) = 1;
    var v1: @TypeOf(v0) = 0;
    require_align_8(&v1); // error: expected type '*align(8) u8', found '*u8'
}
test "002" {
    // anytype is dropping alignment too
    var v0: u8 align(8) = 1;
    generic_8(v0); // error: expected type '*align(8) const u8', found '*const u8'
}
Hello, It's seems that dropping alignment also affect `@TypeOf` and `anytype`, see below. Maybe `const` could be a thing to consider too. I guess if we address this issue, it will also address the issue of `@FieldType`. I do not know if I should create a dedicated bug report. ```zig fn require_align_8(x: *const align(8) u8) void { _ = x; } fn generic_8(x : anytype) void { require_align_8(&x); } ``` ```zig test "001" { // TypeOf Drop alignment const v0: u8 align(8) = 1; var v1: @TypeOf(v0) = 0; require_align_8(&v1); // error: expected type '*align(8) u8', found '*u8' } ``` ```zig test "002" { // anytype is dropping alignment too var v0: u8 align(8) = 1; generic_8(v0); // error: expected type '*align(8) const u8', found '*const u8' } ```

dropping alignment also affect @TypeOf and anytype
...
var v1: @TypeOf(v0) = 0;

@gschwind That is currently by design.
Alignment and modifiability in Zig aren't part of the value types, but of locations (local/global variable/const, field declaration).
Given const c: u8 align(8) and var v: u8, @TypeOf(c) == @TypeOf(v) will hold since (u8) == (u8).
The address-of operator & applies those location attributes to the resulting pointer type, so @TypeOf(&c) != @TypeOf(&v) since (*align(8) const u8) != (*u8).
@FieldType(T, name) yields the declared field type, which also doesn't contains the field's alignment requirement.
Suggested above is a proposal for another builtin @FieldPtr(T, name) / @FieldPtrType(T, name), which would return a pointer type, so contain modifiability and alignment attributes.

> [dropping alignment also affect `@TypeOf` and `anytype`](https://codeberg.org/ziglang/zig/issues/35826#issuecomment-17719103) > [...](https://codeberg.org/ziglang/zig/issues/35826#issuecomment-17719103) > [`var v1: @TypeOf(v0) = 0;`](https://codeberg.org/ziglang/zig/issues/35826#issuecomment-17719103) @gschwind That is currently by design. Alignment and modifiability in Zig aren't part of the value types, but of locations (local/global variable/const, field declaration). Given `const c: u8 align(8)` and `var v: u8`, `@TypeOf(c) == @TypeOf(v)` will hold since `(u8) == (u8)`. The address-of operator `&` applies those location attributes to the resulting pointer type, so `@TypeOf(&c) != @TypeOf(&v)` since `(*align(8) const u8) != (*u8)`. `@FieldType(T, name)` yields the declared field type, which also doesn't contains the field's alignment requirement. Suggested above is a proposal for another builtin `@FieldPtr(T, name)` / `@FieldPtrType(T, name)`, which would return a pointer type, so contain modifiability and alignment attributes.
Sign in to join this conversation.
No milestone
No assignees
5 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ziglang/zig#35826
No description provided.