From aa8d9b6cbcc9e280d6be1641e1ac5771a0e63fe6 Mon Sep 17 00:00:00 2001 From: shadowninja55 <49539636+shadowninja55@users.noreply.github.com> Date: Thu, 1 Jul 2021 05:30:43 -0400 Subject: [PATCH] docs: document custom iterators (#10629) --- doc/docs.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 33aa6ac989..8a598ac75a 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1331,6 +1331,45 @@ println(numbers) // [1, 2, 3] ``` When an identifier is just a single underscore, it is ignored. +##### Custom iterators +Types that implement a `next` method returning an `Option` can be iterated +with a `for` loop. + +```v +struct SquareIterator { + arr []int +mut: + idx int +} + +fn (mut iter SquareIterator) next() ?int { + if iter.idx >= iter.arr.len { + return error('') + } + defer { + iter.idx++ + } + return iter.arr[iter.idx] * iter.arr[iter.idx] +} + +nums := [1, 2, 3, 4, 5] +iter := SquareIterator{ + arr: nums +} +for squared in iter { + println(squared) +} +``` + +The code above prints: +``` +1 +4 +9 +16 +25 +``` + ##### Map `for` ```v