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,
};
}