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

Can't use labeled block as if body? #5108

Closed
donaldcallen opened this issue Apr 19, 2020 · 5 comments
Closed

Can't use labeled block as if body? #5108

donaldcallen opened this issue Apr 19, 2020 · 5 comments

Comments

@donaldcallen
Copy link

This code:

comptime std.debug.assert(builtin.single_threaded);
            const cache = struct {
                var maybe_statement: ?*s.sqlite3_stmt = null;
            };
            if (cache.maybe_statement) |stmt| stmt
            else :miss {
                cache.maybe_statement = zlib.prepare_statement([*:0]const u8, globals.db,
                    queries.account_child_all_sql);;
                break :miss cache.maybe_statement orelse unreachable;
            }

Results in this error:

zig build-exe --main-pkg-path .. --single-threaded `pkg-config --libs gtk+-3.0` -L/usr/local/lib -L/usr/lib -lc -lsqlite3 newcash.zig
./book.zig:78:18: error: invalid token: ':'
            else :miss {
                 ^

I am trying to use the if as expression, returning a value from either leg of the if. The else side
involves more than one statement, so I believe I need to use a labeled block to return a value from it. The compiler isn't buying it. Comments? Suggestions?

@donaldcallen
Copy link
Author

Forgot to mention -- I am using zig-linux-x86_64-0.6.0+986aa42d3.tar.xz on an up-to-date
Slackware current system.

@SpexGuy
Copy link
Contributor

SpexGuy commented Apr 19, 2020

The : goes on the right side of the label when specifying it and the left when referencing it. So it should be

else miss: {
    ...
    break :miss <return value>;
}

We should probably call that out specifically in the docs, it's kind of hard to see.

@Tetralux
Copy link
Contributor

Tetralux commented Apr 19, 2020

... Or we could remove the need for the : when referencing it 😁

else miss: {
    break miss ret_val;
};

@donaldcallen
Copy link
Author

Thank you very much.

I will comment that this is a bit of syntax that merits reconsideration.

@squeek502
Copy link
Collaborator

Relevant proposal: #5083

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants