How to store constant pointers in a buffer at compile time?

I tested the following code, and they can all assign values to variables at compile time.


test "comptime" {
    const num: usize = 0;
    comptime {
        var ptr: *const anyopaque = undefined;
        ptr = #
    }
    comptime {
        var array: [10]*const anyopaque = undefined;
        for (&array) |*item| {
            item.* = #
        }
    }
    comptime {
        var buf: [64]u8 = undefined;
        const slice: []align(1) usize = std.mem.bytesAsSlice(usize, &buf);
        slice[0] = 100;
    }
    comptime {
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = std.mem.bytesAsSlice(*const anyopaque, &buf);
        slice[0] = @ptrFromInt(100);
    }
}

But when I tried another piece of code, it resulted in an error.

test "comptime_error" {
    comptime {
        const num1: usize = 0;
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = (std.mem.bytesAsSlice(*const anyopaque, &buf));
        slice[0] = &num1;
    }
}
 error: value stored in comptime field does not match the default value of the field
        slice[0] = &num1;
        ~~~~~~~~~^~~~~~~

Why does this happen? If the previous code snippets work, why does this one result in an error?

Can this issue be resolved?

I was unable to reproduce this error due to encountering a segment fault. :joy:

const std = @import("std");
test "comptime_error" {
    comptime {
        const num1: usize = 0;
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = (std.mem.bytesAsSlice(*const anyopaque, &buf));
        slice[0] = &num1;
    }
}

I tested two versions of zig on the Debian operating system, including master and 0.15.2, and both encountered segmentation faults… On what operating system and version did OP get a compilation error?

npc1054657282@localhost:~/projects/zig-tests$ /home/npc1054657282/.vscode-server/data/User/globalStorage/ziglang.vscode-zig/zig/x86_64-linux-0.16.0-dev.2905+5d71e3051/zig test test.zig
Segmentation faultg
npc1054657282@localhost:~/projects/zig-tests$ /home/npc1054657282/.vscode-server/data/User/globalStorage/ziglang.vscode-zig/zig/x86_64-linux-0.15.2/zig test test.zig
Segmentation fault