新的可迭代类型
在 Julia 中,当循环遍历可迭代对象时,使用 for 语法完成 I :
for i = I   # or  "for i in I"
    # body
end
在幕后,这被翻译为:
state = start(I)
while !done(I, state)
    (i, state) = next(I, state)
    # body
end
因此,如果你希望 I 是可迭代的,则需要为其类型定义 start,next 和 done 方法。假设你将包含数组的类型 Foo 定义为以下字段之一: 
type Foo
    bar::Array{Int,1}
end
我们通过执行以下操作来实例化 Foo 对象:
julia> I = Foo([1,2,3])
Foo([1,2,3])
julia> I.bar
3-element Array{Int64,1}:
 1
 2
 3
如果我们想迭代 Foo,每次迭代返回每个元素 bar,我们定义方法:
import Base: start, next, done
start(I::Foo) = 1
next(I::Foo, state) = (I.bar[state], state+1)
function done(I::Foo, state)
    if state == length(I.bar)
        return true
    end
    return false
end
请注意,由于这些函数属于 Base 模块,因此在向其添加新方法之前,我们必须先知道它们的名称。
定义方法后,Foo 与迭代器接口兼容:
julia> for i in I
           println(i)
       end
1
2
3