#Initialize const array of structs with slice fields

1 messages · Page 1 of 1 (latest)

formal dove
#

Lets say I have the following struct:
const test_struct: type = struct { a: []u8, };
I want to have something like this:
const arr = [_]test_struct{ .{ .a = "a" }, .{ .a = "b" } };
I dont care to mutate any of the data (would also like to know how I would go about this if I wanted the data to be mutable).
How do I do this?

calm trail
#

If you want it to be mutable though, then you ultimately need to decide where the memory is going to live.
If on the stack, you want var buf: [32]u8 = undefined; and then use &buf or buf[0..n] will yield a []u8.
Otherwise, you'd need to use an allocator.

#

You could also make buf a global variable instead of on the stack, and that would work for mutable too - but that's generally not what you want.

formal dove
#

thanks