Can i have a range as function parameter?

is there a way to do something of the sorts:

fn get_items(self: *Self, index: Range) -> []Self
{
    ...
}

const items = <Type>.get_items(0..5);

only solution i found so far is to use an array of size two [start, end], or a struct with two members {start: usize, end: usize}.
both are somewhat ok, but not as convenient to use.

Wh not use a slice?

Zig does not have a syntax equivalent of a Range. You would have to do what you have already tried. An array of 2 integeres or a struct.

I personally would choose the struct and give a default start of 0 so that it could be something like:

const items = <Type>.getItems(.{ .end = 5 });

You may also want to take look at ziter if this is really what you want.

Welcome to the forums! :slight_smile:

The .. and ... tokens aren’t ‘real’ operators. They don’t produce a value. Outside of the places where they’re valid syntax (loops, switches, arrays, slices), they don’t compile. So no, there’s no way to do that.

There’s lots of ways you could approach it if you want more type safety, but the two methods you’ve already found are pretty much what you get if you want a single range parameter.

But why not just pass two parameters and assert that they’re a valid range?

2 Likes

alright thanks for the quick responses.

But why not just pass two parameters and assert that they’re a valid range?

i find it more consistent and thus readable if i can index custom types the same way as i would an array or slice.
oh well, i will make do with a struct.

I created something, maybe I shouldn’t have?

2 Likes