I might be missing something simple, but I’ve struggled to no avail.
I want a struct that contains an array of comptime-known size (provided by calling code). I could do this like so:
fn Foo(comptime size: usize) type {
return struct {
bar: [size]u8,
};
}
But, using this might be a little more awkward than some of the simpler cases I’ve seen. One might want to:
var f = Foo(5) {
.bar = [_]u8{0} ** 5,
};
A little unDRY, but more importantly, if I wanted to provide some more useful initialization, I might prefer the user have an experience like:
var f = Foo(5); // or create_foo(5); -- anything would do
Which resulted in a bar initialization including setting bar[0] = 100, bar[1] = yadda… and so on. I can’t get wrapped around how to do this because something like:
fn create_foo(comptime size: usize) FooType {
var result = Foo(size);
result.f[size-1] = 7;
return result;
}
Would need FooType to be defined, but my Foo requires a comptime parameter, so there’s no normal “const Foo = struct { …” Of course I could ask my caller to do something like:
init_foo(Foo(5), 5);
And make:
fn init_foo(comptime T: type, size: usize) T {
var result = T {
.bar = [_]u8{0} ** 5,
}
result.bar[0] = 17;
return result;
}
but this also feels contrived and unDRY. I could break init into two steps and require the calling code to:
f = Foo(5);
f.init();
But I don’t love that, and my real code includes some const arrays in the struct which can’t be modified after the instance is forged, anyway, so two-stepping isn’t an option. How do I achieve calling code that looks like this:
f = create_foo(5);
and results in a struct of my definition, which contains an array stack-sized to 5, and also (preferably) initialized beyond? Thank you in advance for any hints you have!