1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: document custom iterators (#10629)

This commit is contained in:
shadowninja55 2021-07-01 05:30:43 -04:00 committed by GitHub
parent 8b901df366
commit aa8d9b6cbc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1331,6 +1331,45 @@ println(numbers) // [1, 2, 3]
``` ```
When an identifier is just a single underscore, it is ignored. 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` ##### Map `for`
```v ```v