# 迭代器的通用可变和非可变参数

kfa6706

``````iterator testI[T](arr: seq[T]): T =
# I don't want to copy-paste this body
# In a real world example it might be much bigger
for i in 0 ..< arr.len:
yield arr[i]
``````

``````for i in testI(@[1,2,3]):
echo i
``````

``````var lst = @[1,2,3]
for i in testI(lst):
i += 1
echo i
``````

``````iterator testI[T](arr: var seq[T]): var T =
# I don't want to copy-paste this body
# In a real world example it might be much bigger
for i in 0 ..< arr.len:
yield arr[i]
``````

``````proc foo[A, B](x: A, fn: B) =
fn(x)

var x = 1
foo(x, proc(x: var int) = x += 1)
foo(1, proc(x: int) = echo x)
assert x != 1
``````

``````iterator testI[A, B](arr: A): B =
# I don't want to copy-paste this body
# In a real world example it might be much bigger
for i in 0 ..< arr.len:
yield arr[i]
var lst = @[1,2,3]
for i in testI[var seq[int], var int](lst):
i += 1
``````

xbello

``````template myCycle =
## Long and tedious code here.
for i in 0 ..< arr.len:
yield arr[i]

iterator testI[T](arr: seq[T]): T =
echo "Non-var type"
myCycle

iterator testI[T](arr: var seq[T]): var T =
echo "Var type"
myCycle

var lst1 = @[1,2,3]
for i in testI(lst1):
echo i

let lst2 = @[1,2,3]
for i in testI(lst2):
echo i
``````

``````iterator testI[T](a: var openArray[T]): var T {.inline.} =
var i = 0
while i < len(a):
yield a[i]
inc(i)

var lst = @[1, 2, 3]
for i in testI(lst):
i += 1

echo lst
# @[2, 3, 4]
``````

``````var lst = @[1, 2, 3]
for i in mitems(lst):
i += 1

echo lst
# @[2, 3, 4]
``````

0 条评论