How can I initialize only the .len part of a slice?

At some point I know only the length of a slice and I don’t want to waste space for a separate length variable/struct field. So I want to set .len of the slice and later set the .ptr part.

return MyStruct{ .my_slice = i_dont_know_the_ptr[0..good_len] };

Hi! You can try setting them like this:

var my_slice: []MyType = undefined;
my_slice.len = my_len;
my_slice.ptr = my_ptr;

@tensorush is correct - you can create an empty slice and then set the length to whatever you want.

Here’s how you can do that (assuming that items is a slice):

.items = &[_]T{};
.items.len = // whatever you would like

Can you give us some more information on what is prompting you to do this? It’s not unreasonable to alter the length of a slice, but I’ve not seen someone set it’s length before the pointer :slight_smile:

Also, welcome to the forum @Zergling

1 Like

Hi @AndrewCodeDev ,

OK, now I have this and it seems to work:

fn makeSlice(comptime T: type, len: usize) []T {
    var s: []T = undefined;
    s.len = len;
    return s;

I’d like to make a more refined post about this tomorrow when I have a compiler on hand - I’m still curious about your use case for this?