Search code examples
zig

Does Zig call defer after block breaks?


Given the following snippet, does the call to unlock occur after the break or before?

var input_data: InputState = blk: {
    user.input_mutex.lock();
    defer user.input_mutex.unlock();
    break :blk user.input;
};

Solution

  • The documentation says:

    defer will execute an expression at the end of the current scope.

    It's not worded very clearly, but it means that the defer statements are executed after all of the code in the current block has been executed. This includes break statements.

    For example, an errdefer statement cannot be executed before the last line, because errdefer statements are only enabled after return error.SomeError, which would be the last line in a function.