Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: allow switch on packed struct #22214

Open
mlugg opened this issue Dec 12, 2024 · 2 comments
Open

Proposal: allow switch on packed struct #22214

mlugg opened this issue Dec 12, 2024 · 2 comments
Labels
accepted This proposal is planned. proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone

Comments

@mlugg
Copy link
Member

mlugg commented Dec 12, 2024

This proposal is a simple extension of #21678. The following code should compile:

const S = packed struct {
    a: u1,
    b: u1,
    fn foo(s: S) bool {
        return switch (s) {
            .{ .a = 0, .b = 1 }, .{ .a = 1, .b = 0 } => true,
            else => false,
        };
    }
};

test "switch on packed struct "{
    try expect(S.foo(.{ .a = 1, .b = 0 }));
    try expect(!comptime S.foo(.{ .a = 0, .b = 0 }));
}

const expect = @import("std").testing.expect;

This will require re-introducing result types for switch items, which were removed way back in 85e94fe. They were removed to prepare for #2473, but that proposal has since been un-accepted.

@mlugg mlugg added proposal This issue suggests modifications. If it also has the "accepted" label then it is planned. accepted This proposal is planned. labels Dec 12, 2024
@mlugg mlugg added this to the 0.15.0 milestone Dec 12, 2024
@tauoverpi
Copy link
Contributor

tauoverpi commented Dec 20, 2024

Does this mean similar to the following is now possible?:

const T = packed struct {
    car: type,
    cdr: type,
};

fn lift(comptime value: anytype) type {
    return packed struct {
        pub const value = value;
    }
}

const fun = opaque {};

switch (@as(T, some_structure)) {
    .{ .car = bool, .cdr = lift(true) } => {}, // ...
    .{ .car = u8, .cdr = lift(0) } => {}, // ...
    .{ .car = fun, .cdr = .{
        .car = struct { u8, []const u8 },
        .cdr = void,
    } } => {}, // ...
    else => comptime unreachable,
}

@Rexicon226
Copy link
Contributor

Packed structs cannot contain type as they have no guaranteed in-memory representation. This proposal does nothing to change that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted This proposal is planned. proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Projects
None yet
Development

No branches or pull requests

3 participants