Trying to understand what an underscore before assignment means

I am trying to learn zig and was looking at some code examples to understand the syntax of the language. The only thing that I have seen and have not been able to understand is an underscore before an assignment, seemingly assigning something to nothing. The example was a for loop that went like this.

for (array, &array) |val, *ref| {
    _ = val;
    _ = ref
}

I have tried to search what this is but can’t seem to find anything. I would love to read into it myself but need to at least know what I could look up. Any pointers or explanations would be greatly appreciated!

1 Like

This is just like golang, to avoid unused variable error, you mark it as used by “assigning” it to underscore. It’s also easier for reviewer to notice that something is never used. See also: variables - What is "_," (underscore comma) in a Go declaration? - Stack Overflow

Thanks for the clarification! I haven’t learned Golang. So this would be a way to simply prevent an LSP and/or compiler from throwing a warning? That would make sense in the instance of an example as it was mostly to demonstrate how you would create a for loop without going into an example of what you may do inside of the loop.

edit: after reading through the link this make a lot more sense. Thank you for your help!

So this would be a way to simply prevent an LSP and/or compiler from throwing a warning?

Yep, it’s also useful for ignoring captured values, but in zig’s case, it’s a hard error.

test {
    var array: [2]u8 = .{ 0, 0 };

    // all captured values are unued
    for (array, &array) |_, _| {}

    // only use val
    for (array, &array) |val, _| {
        std.debug.print("{d}\n", .{val});
    }
}
2 Likes