对于代码
for i in list
#code
end
可以解释为
next = iterate(iter)
while next !== nothing
(i, state) = next
# body
next = iterate(iter, state)
end
其中要注意的是iterator方法有两个
于是这样定义第一个方法
Base.iterator(list::List{T}) where T = list.size==0 ? nothing : (list.head,list.head)
第二个方法
Base.iterator(list::List{T},state) where T =
begin
state.next==nothing ? nothing : (state.next,state.next)
end
需要注意的是state第一次被赋值是在 (i, state) = next
这里,state的值会被当作参数被下一个iterator(list,state)
调用
这里显示调试结果