Returning an iterator will compile

Hello.
I’m learning zig and reading this blog on zig iterator and I was surprised to learn that when returning an iterator instead of [][]const u8 in the wrap function , the code will compile.
I do understand why the wrap function (see below) will not compile because the compiler will not know the length of the slice of string at compile.

// []const u8 is Zig's str
fn wrap(text: []const u8, width: usize) [][]const u8

But when the wrap function is modified to return an iterator, it will compile. Please explain why returning an iterator changes this.

/// Returns an iterator that wraps text into lines of at most `width`
/// characters, attempting to break on the last space in each line.
pub fn wrap(text: []const u8, width: usize) TextWrapIterator {
    return .{
        .text = text,
        .width = width,
    };
}

It’s hard to know exactly why it’s not compiling without seeing the actual error message that you’re getting. That would help a lot.

Edit: Ok I read that part of the linked blog post and now I understand the situation better.

It’s the issue of not knowing in advance how many of a list of things you might end up with, and thus you would need to allocate on the heap as necessary. In this scenario, you can avoid heap allocations by iterating over the input in fixed-size chunks and then returning those slices one-at-a-time when requested.

2 Likes