Skip to content

Possible compiler bug involving packed structs/enums/unions #16581

@saltzm

Description

@saltzm

Zig Version

0.11.0-dev.4263+f821543e4

Steps to Reproduce and Observed Behavior

This is the broken example, made as minimal as possible: Godbolt
Removing "packed" from everything makes it work (as do a few other small changes, noted in comments): Godbolt

Here's the code, for convenience. It code should output "READ" but outputs "INSERT" instead.

const std = @import("std");

// If I make these structs have no fields, it works fine.
const ReadRequest = packed struct { key: i32 };
const InsertRequest = packed struct { entry: i32 };

const RequestType = enum {
    read,
    insert,
};

const RequestUnion = packed union {
    read: ReadRequest,
    insert: InsertRequest,
};

const Request = packed struct {
    active_type: RequestType,
    request: RequestUnion, // If I change this to an i32, it works fine.
    const Self = @This();

    fn initReadRequest(read: ReadRequest) Self {
        std.debug.print("\ninitReadRequest\n", .{});
        return Self{
            .active_type = RequestType.read,
            .request = RequestUnion{ .read = read },
        };
    }

    fn initInsertRequest(insert: InsertRequest) Self {
        return Self{
            .active_type = RequestType.insert,
            .request = RequestUnion{
                .insert = insert,
            },
        };
    }
};

pub fn main() void {
    const r = Request.initReadRequest(ReadRequest{.key = 3});
    switch (r.active_type) {
        .read => std.debug.print("READ\n", .{}),
        .insert => std.debug.print("INSERT\n", .{})
    }
}

Expected Behavior

I expected it to output "READ" instead of "INSERT".

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviormiscompilationThe compiler reports success but produces semantically incorrect code.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions