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

Switch statement type inference issues with !?<type> #2899

Closed
ntgraff opened this issue Jul 15, 2019 · 0 comments
Closed

Switch statement type inference issues with !?<type> #2899

ntgraff opened this issue Jul 15, 2019 · 0 comments
Labels
bug Observed behavior contradicts documented or intended behavior
Milestone

Comments

@ntgraff
Copy link

ntgraff commented Jul 15, 2019

In the following code, notNull is always null:

const std = @import("std");

fn maybe2(num: u32) anyerror!?u32 {
    return num;
}

fn maybe(should: enum{Yes, No}, num: u32) anyerror!?u32 {
    return switch (should) {
        .Yes => maybe2(num),
        else => null,
    };
}

test "incorrect return" {
    const notNull = maybe(.Yes, 12) catch unreachable;
    // error: attempt to unwrap null
    std.testing.expect(notNull.? == 12);
}

The following cases work as expected:

const std = @import("std");

fn maybe2(num: u32) ?u32 {
    return num;
}

fn maybe(should: enum{Yes, No}, num: u32) ?u32 {
    return switch (should) {
        .Yes => maybe2(num),
        else => null,
    };
}

test "incorrect return" {
    const notNull = maybe(.Yes, 12);
    std.testing.expect(notNull.? == 12);
}
const std = @import("std");
fn maybe(should: enum{Yes, No}, num: u32) anyerror!?u32 {
    return switch (should) {
        .Yes => num,
        else => null,
    };
}

test "incorrect return" {
    const notNull = maybe(.Yes, 12) catch unreachable;
    std.testing.expect(notNull.? == 12);
}
const std = @import("std");

fn maybe2(num: u32) ?u32 {
    return num;
}

fn maybe(should: enum{Yes, No}, num: u32) anyerror!?u32 {
    return switch (should) {
        .Yes => maybe2(num),
        .No => null,
    };
}

test "incorrect return" {
    const notNull = maybe(.Yes, 12) catch unreachable;
    std.testing.expect(notNull.? == 12);
}

In the first example, replacing else with .No, you get error: expected type 'u32', found '(null)' when compiling. Zig version is 0.4.0+7d9ee5d6d

@andrewrk andrewrk added this to the 0.5.0 milestone Jul 16, 2019
@andrewrk andrewrk added the bug Observed behavior contradicts documented or intended behavior label Jul 16, 2019
LemonBoy added a commit to LemonBoy/zig that referenced this issue Sep 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants