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?