I don't think there's a way to directly assign a smaller array to a larger one, but you can always create a helper function to do so:
fnarray(comptimeT:type,comptimesize:usize,items:?[]constT)[size]T{varoutput=std.mem.zeroes([size]T);if(items)|slice|std.mem.copy(T,&output,slice);returnoutput;}constA=struct{foo:[10]u8,};// fully initializevarfoo:[3]u8=.{'f','o','o'};// zero initialize then copy desired contentsvarbar:[50]u8=[_]u8{0}**50;std.mem.copy(u8,&bar,"bar");varbaz:A=A{.foo=[_]u8{0}**10};std.mem.copy(u8,&baz.foo,"baz");// fully initialize with comptime concatenationvarbar_full:[50]u8="bar".*++[_]u8{0}**47;varbaz_full:A=A{.foo="baz".*++[_]u8{0}**7};// with helper functionvarbar_alt=comptimearray(u8,50,"bar");varbaz_alt=A{.foo=comptimearray(u8,10,"baz")};
Thanks - great to see different options for how to do it!
Can you think of a way to use the helper function and somehow infer the size of the struct member so it doesn't have to be repeated? Not a huge deal but I can't figure out how to do it.
I don't know how to do that exactly. The closest I could come up with would be to leave the array undefined and use a helper function to fill it in, but that has slightly different semantics since the memcpy is a little more explicit:
I don't think there's a way to directly assign a smaller array to a larger one, but you can always create a helper function to do so:
Thanks - great to see different options for how to do it!
Can you think of a way to use the helper function and somehow infer the size of the struct member so it doesn't have to be repeated? Not a huge deal but I can't figure out how to do it.
I don't know how to do that exactly. The closest I could come up with would be to leave the array
undefined
and use a helper function to fill it in, but that has slightly different semantics since thememcpy
is a little more explicit:Good solution. I haven't seen std.meta.Elem before so I'm going to go read up on that. Thanks!