Skip to content

Commit aa8d9b6

Browse files
docs: document custom iterators (#10629)
1 parent 8b901df commit aa8d9b6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

doc/docs.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1331,6 +1331,45 @@ println(numbers) // [1, 2, 3]
13311331
```
13321332
When an identifier is just a single underscore, it is ignored.
13331333

1334+
##### Custom iterators
1335+
Types that implement a `next` method returning an `Option` can be iterated
1336+
with a `for` loop.
1337+
1338+
```v
1339+
struct SquareIterator {
1340+
arr []int
1341+
mut:
1342+
idx int
1343+
}
1344+
1345+
fn (mut iter SquareIterator) next() ?int {
1346+
if iter.idx >= iter.arr.len {
1347+
return error('')
1348+
}
1349+
defer {
1350+
iter.idx++
1351+
}
1352+
return iter.arr[iter.idx] * iter.arr[iter.idx]
1353+
}
1354+
1355+
nums := [1, 2, 3, 4, 5]
1356+
iter := SquareIterator{
1357+
arr: nums
1358+
}
1359+
for squared in iter {
1360+
println(squared)
1361+
}
1362+
```
1363+
1364+
The code above prints:
1365+
```
1366+
1
1367+
4
1368+
9
1369+
16
1370+
25
1371+
```
1372+
13341373
##### Map `for`
13351374

13361375
```v

0 commit comments

Comments
 (0)