I have a little example here where I’d like to take advantage of structural typing or duck-typing;
const std = @import("std");
test "JSON parsing" {
const basic =
\\{"foo":"bar"}
;
const out = try std.json.parseFromSlice(
struct { foo: []const u8 },
alloc,
basic,
.{}
);
defer out.deinit();
try std.testing.expectEqualDeep(.{ .foo = "bar" }, out.value);
}
This won’t compile because out.value and .{ .foo = “bar” } are different anonymous structs despite being structurally the same.
/Users/johndevries/.local/quickzilver/lib/std/testing.zig:737:15: error: incompatible types: 'langlearn.test.JSON parsing__struct_30574' and 'langlearn.test.JSON parsing__struct_30512'
const T = @TypeOf(expected, actual);
^~~~~~~~~~~~~~~~~~~~~~~~~
/Users/johndevries/.local/quickzilver/lib/std/testing.zig:737:23: note: type 'langlearn.test.JSON parsing__struct_30574' here
const T = @TypeOf(expected, actual);
^~~~~~~~
/Users/johndevries/.local/quickzilver/lib/std/testing.zig:737:33: note: type 'langlearn.test.JSON parsing__struct_30512' here
const T = @TypeOf(expected, actual);
^~~~~~
src/langlearn.zig:27:36: note: called inline here
try std.testing.expectEqualDeep(.{ .foo = "bar" }, out.value);
~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
test_0: src/root.zig:13:17
I get that I can fix this by naming the struct used in both places as follows;
test "JSON parsing" {
const basic =
\\{"foo":"bar"}
;
const Basic = struct { foo: []const u8 };
const out = try std.json.parseFromSlice(
Basic,
alloc,
basic,
.{}
);
defer out.deinit();
try std.testing.expectEqualDeep(Basic{ .foo = "bar" }, out.value);
}
But I wonder whether there’s a reason I can’t get this to work in the duck-typing / structural-typing style.