Hello, I have two structs that are defined like so:
- NodeX carries a list of pointers of NodeY
- NodeY carries a list of pointers of NodeX
A bipartite graph so to speak.
Now you can imagine, there is a lot of potential code duplication, so I wish to use a function that generates type NodeX, NodeY.
However, when I write the following code, it does not compile.
const std = @import("std");
const print = std.debug.print;
const ArrayList = std.ArrayList;
const Allocator = std.mem.Allocator;
const NodeXX = struct {
list: ArrayList(*NodeYY),
fn init(allocator: Allocator) error{OutOfMemory}!@This() {
return @This(){
.list = try .initCapacity(allocator, 0),
};
}
fn deinit(self: *@This(), allocator: Allocator) void {
self.list.deinit(allocator);
self.* = undefined;
}
};
const NodeYY = struct {
list: ArrayList(*NodeXX),
fn init(allocator: Allocator) error{OutOfMemory}!@This() {
return @This(){
.list = try .initCapacity(allocator, 0),
};
}
fn deinit(self: *@This(), allocator: Allocator) void {
self.list.deinit(allocator);
self.* = undefined;
}
};
pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
defer {
const leaked = gpa.deinit() == .leak;
if (leaked) @panic("leak detected");
}
const a = gpa.allocator();
var c: NodeXX = try .init(a); // replace to NodeX for manual code generation
defer c.deinit(a);
print("All good\n", .{});
}
How can I make it work?