# Proper way to cast comptime data to \`anyopaque\`

**URL:** <https://ziggit.dev/t/proper-way-to-cast-comptime-data-to-anyopaque/7283>\
**Category:** Help\
**Tags:** comptime\
**Created:** [December 11, 2024, 11:57pm UTC](https://ziggit.dev/t/proper-way-to-cast-comptime-data-to-anyopaque/7283 "2024-12-11T23:57:54Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Sze](https://ziggit.dev/user_avatar/ziggit.dev/sze/32/496_2.png) [@Sze](https://ziggit.dev/u/Sze)\
**Post date:** [December 12, 2024, 5:42am UTC](https://ziggit.dev/t/proper-way-to-cast-comptime-data-to-anyopaque/7283/2 "2024-12-12T05:42:13Z")

</div>

Hi @ExpandingMan welcome to Ziggit!

You can assign your var to a const and then use that const in the return value instead. That way the return value doesn’t directly refer to a comptime var anymore and is seen as static data that doesn’t refer back to comptime.  
For a full explanation read this:

> [@Comptime-Mutable Memory Changes](https://ziggit.dev/t/comptime-mutable-memory-changes/3702):
>
> Hi everyone! Recently, PR [#19414](https://github.com/ziglang/zig/pull/19414) was merged, which more-or-less rewrote the compiler’s internal implementation of comptime var. This rewrite comes with some language changes, so I thought I’d explain the user-facing impact of this PR here so that people know what’s going on when they inevitably get errors TL;DR A pointer to a comptime var is never allowed to become runtime-known, to be contained within the resolved value of a declaration, or to be otherwise referenced by analysis of any declara…

So I think this should work:

```zig
fn buildfield(comptime name: [:0]const u8, comptime typ: type, comptime opts: anytype) Type.StructField {
    comptime var default_value: ?*const anyopaque = null;
    comptime var is_comptime: bool = false;
    comptime var alignment: comptime_int = @alignOf(typ);
    inline for (meta.fields(@TypeOf(opts))) |opt| {
        if (mem.eql(u8, opt.name, "default_value")) {
            default_value = @ptrCast(&@field(opts, opt.name));
        } else if (mem.eql(u8, opt.name, "is_comptime")) {
            is_comptime = @field(opts, opt.name);
        } else if (mem.eql(u8, opt.name, "alignment")) {
            alignment = @field(opts, opt.name);
        } else {
            @compileError("got bogus argument for buildfield option");
        }
    }
    const frozen_default_value = default_value;
    const frozen_is_comptime = is_comptime;
    const frozen_alignment = alignment;
    return Type.StructField{
        .name = name,
        .type = typ,
        .default_value = frozen_default_value,
        .is_comptime = frozen_is_comptime,
        .alignment = frozen_alignment,
    };
}

```

---

_[View the full topic](https://ziggit.dev/t/proper-way-to-cast-comptime-data-to-anyopaque/7283)._
