So, as far as I understand, when we use @This() inside a struct, union, etc. It refers to the type/container itself, right? In this case, const T = union { ... }, so @This() refers to that anonymous union.
But what happens when @This() is used outside an explicitly declared struct, union, etc?
For example, I came across this code in zigtools/zls (DiagnosticsCollections.zig):
//! Collects various sources of error messages to be sent out as LSP diagnostics.
const std = @import("std");
const lsp = @import("lsp");
const tracy = @import("tracy");
const offsets = @import("offsets.zig");
const Uri = @import("Uri.zig");
io: std.Io,
allocator: std.mem.Allocator,
mutex: std.Io.Mutex = .init,
tag_set: std.array_hash_map.Auto(Tag, struct {
version: u32 = 0,
error_bundle_src_base_path: ?[]const u8 = null,
error_bundle: std.zig.ErrorBundle = .empty,
diagnostics_set: Uri.ArrayHashMap(struct {
arena: std.heap.ArenaAllocator.State = .{},
diagnostics: []lsp.types.Diagnostic = &.{},
error_bundle: std.zig.ErrorBundle = .empty,
}) = .empty,
}) = .empty,
outdated_files: Uri.ArrayHashMap(void) = .empty,
transport: ?*lsp.Transport = null,
offset_encoding: offsets.Encoding = .@"utf-16",
const DiagnosticsCollection = @This();
// The rest of the code...
Here, there is no explicit struct DiagnosticsCollection { ... } surrounding these fields. So what exactly does @This() refer to in this case?
Is the file itself implicitly acting as the struct/container? And if so, why do we define:
const DiagnosticsCollection = @This();
instead of explicitly wrapping everything in a struct like:
const DiagnosticsCollection = struct {
io: std.Io,
allocator: std.mem.Allocator,
// ...
};
I’m trying to understand what is happening under the hood here and why this pattern is used in Zig.