3 ms·
While with optionals enables some iterator-like behavior. https://ziglang.org/documentation/master/#while-with-Optionals https://ziglang.org/documentation/maste
by Jayschwa 4y ago
While with optionals enables some iterator-like behavior. https://ziglang.org/documentation/master/#while-with-Optionals https://ziglang.org/documentation/master/#while-with-Optiona...
- malcolmstill 4y agoTo expand on the parent and grandparent: Laremere is correct in that there is no "magic" built-in understanding of iterators in the language, i.e. under the hood calling a `.next()` method, without explicitly having to call it. That _would_ violate the no hidden flow control maxim. However, as Jayschwa points out, Zig's `while` loop will bind the result of its expression (in its own block scope) if it is non-null and otherwise exit the loop. This gives you essentially the same as a for loop that has some language-level knowledge of the iterator pattern, except there is no hidden flow control (I have to explicitly call `next`). And indeed the Zig standard library is replete with iterators (and in most of the Zig code I write I will will write iterators for my own collections). For example, `mem.split` returns an iterator: var it = mem.split(...); // it.next() returns null after we run out of // split text and the while loop exits while (it.next()) |substr| { // In here we have a non-nil substr } > Plus I imagine it's a lot easier for the compiler to perform optimizations this way. That's an interesting point: does Zig miss out on some optimisation possibilities with iterators given they are not a language-level construct? I don't know.