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;
};
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.
Yes, at least as of zig version 0.12.0-dev.167+dd6a9caea
Running the following snippet:
const std = @import("std");
fn getRandom() !u64 {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
std.debug.print("test seed: {}\n", .{seed});
return seed;
}
pub fn main() !void {
var value = blk: {
defer std.debug.print("defer test seed\n", .{});
break :blk try getRandom();
};
_ = value;
}
Will show the following in console output:
test seed: 6866361107008308078
defer test seed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With