#Unknown Array Length in fn

1 messages · Page 1 of 1 (latest)

orchid gorge
#

Hey all! I'm extremely new to Zig, and I've found a lot of helpful resources, but I might be overcomplicating this.

What is the best way to write a function that accepts an array of unknown length, does something, and returns them? (Or it could be a pointer)

Something similar to the following:

pub fn main() !void {
    const nums = [_]i32{ 3, 4, 5, 6 };

    const numsOutput = example(nums);
    _ = numsOutput;
}

fn example(nums: []i32) []i32 {
    // we would mess with nums a bit here
    return nums;
}

Is the best way to do this an Allocator? If so, I can use that; just wondering if I'm overcomplicating this (or missing a better way)
Thanks in advance for any help! ❤️

#

Unknown Array Length in fn

lilac zealot
#

[]i32 is a pointer so i dont see why you'd return it. unless you dont want to mutate the original and instead return a mutated copy, which then yes you'd need an allocator

orchid gorge
#

Thanks! I'll do research after this as to why that's a pointer; but how can I make this example work with a pointer, then?

#

oh wait

lilac zealot
#

[]i32 is a slice type, which is just a pointer and a length (you could imagine it as { ptr: [*]T, len: usize })

the only reason that example wouldnt work is because youre trying to get a mutable slice when nums is const (and you need & to coerce it into a slice). im assuming because you made nums const you want to return a new array of numbers that you've modified, which you'd need an allocator for.

#

[]const i32 would be a const slice

orchid gorge
#

thanks!
For my example, actually all I had to do was change const numsOutput = example(nums) -> const numsOutput = example(&nums); (which the compiler told me to do)
but then I got a scary error message (expected type '[]i32', found '*const [4]i32')
all I had to do then was change the const nums to var nums 😛

#

Thanks though! You've definitely given me a lot of insight and stuff to research! Greatly appreciate it :D

lilac zealot
#

np! doing that would change nums itself so you wouldnt need to return anything