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:
Yep, tried a couple ways but can't seem to get around having to manually specify the type in some way rather than being able to infer it. Slight variant I came up with specifically for string literals only:
fnstringLiteralToArray(comptimeliteral:[]constu8,ArrayType:type)ArrayType{constti=@typeInfo(ArrayType);comptime{assert(ti==.Array);assert(ti.Array.len>=literal.len);}returnliteral[0..literal.len].*++.{0}**(ti.Array.len-literal.len);}// Non-field variables can infer the typevarstring_buffer=stringLiteralToArray("A default value",[64]u8);// Struct fields need to specify both sadlyconstSomeStruct=struct{field:[32]u8=stringLiteralToArray("Another default",[32]u8),};
For further actions, you may consider blocking this person and/or reporting abuse
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!
Yep, tried a couple ways but can't seem to get around having to manually specify the type in some way rather than being able to infer it. Slight variant I came up with specifically for string literals only: