Skip to content

Modifying slices with comptime-only types in comptime #23021

@AMythicDev

Description

@AMythicDev

Zig Version

0.14.0-dev.3367+1cc388d52

Steps to Reproduce and Observed Output

This code:

const std = @import("std");

const TestStruct = struct { field1: u32, field2: f64 };

pub fn main() !void {
    const t = TestStruct{ .field1 = 10, .field2 = 3.14 };

    const tinfo = @typeInfo(@TypeOf(t));

    comptime var fields = @constCast(tinfo.@"struct".fields);
    const tmp = fields[0];
    fields[0] = fields[1];
    fields[1] = tmp;
}

gives the following error message:

test.zig:12:15: error: cannot store comptime-only type 'builtin.Type.StructField' at runtime
    fields[0] = fields[1];
    ~~~~~~~~~~^~~~~~~~~~~
test.zig:12:11: note: operation is runtime due to this pointer
    fields[0] = fields[1];
    ~~~~~~^~~
referenced by:
    posixCallMainAndExit: .zigverm/installs/zig-x86_64-linux-master/lib/std/start.zig:656:37
    _start: .zigverm/installs/zig-x86_64-linux-master/lib/std/start.zig:464:40
    3 reference(s) hidden; use '-freference-trace=5' to see all references

Expected Output

Here I am @constCasting the tinfo.@"struct".fields slice which should not be done.
Instead, the solution to this is to first copy the tinfo.@"struct".fields into a separate buffer and then do the swap operations on it.

I think it would be helpful if the error message pointed out something better than whatever vague it is giving right now.

I have discussed this issue with other Zig community members and they seem to agree that the error message should be improved for this one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    error messageThis issue points out an error message that is unhelpful and should be improved.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions