What is the difference between a tuple and anonymous struct – syntactically, semantically, and implementation wise?
Sometimes I’m not even sure which one I’m using.
What is the difference between a tuple and anonymous struct – syntactically, semantically, and implementation wise?
Sometimes I’m not even sure which one I’m using.
Anonymous struct literals behave like normal structs and have named fields that are accessed with anon.field
syntax. Tuples are anonymous struct literals where the fields don’t have names. Tuple fields are instead accessed via tup[i]
syntax (or tup.@"i"
) and you can use tup.len
to get the number of fields.
pub fn main() void {
const tup = .{ 3.1, "hello" };
const anon = .{ .a = 3.1, .b = "hello" };
@compileLog(tup);
@compileLog(anon);
}
Compile Log Output:
@as(struct{comptime comptime_float = 3.1, comptime *const [5:0]u8 = "hello"}, .{ 3.1, "hello" })
@as(struct{comptime a: comptime_float = 3.1, comptime b: *const [5:0]u8 = "hello"}, .{ .a = 3.1, .b = "hello" })
You can also just create tuple types yourself:
const MyTuple = struct { f32, i32 };
my_tuple: MyTuple = .{ 3.1, -2 };
So there is nothing uniquely different about the types for those anonymous literals, and I was wrong to say that “tuples are anonymous struct literals.”
There are a lot of concepts with similar names:
“Anonymous Struct” = a struct type without a name
return struct {
name: []const u8,
};
All the struct type names are derived.
“Struct Literal” = a struct value
Point{.x = 0, .y = 0}
“Anonymous Struct Literal” = struct literal (value) without a name
const pt: Point = .{.x = 0, .y = 0};
“Tuple” = struct type without field names
const names: struct{[]const u8, []const u8} = .{"John", "Doe"};
“Anonymous Struct Type” = a struct created from an anonymous struct literal with unknown result type
const unknown = .{ .answer = 42};
A tuple is an anonymous struct without field names.
Implementation wise tuple is a struct with field names @“0”, @“1”, …
Syntactically:
Tuple declaration: struct { []const u8, i32}
Struct declaration: struct { name: []const u8, value: i32}
I meant is there any difference in generated code?
The fields are all comptime so it’s hard to see how generated code can be different.