CYKun
2018-04-13 13:00:39 +08:00
看维基里关于生成器的解释:
A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately.
生成器类似于一个返回值为数组的函数;不同于普通函数直接构造并返回( return )整个数组的做法,生成器每次返回( yield )其中的一个值。
从行文里对 yield 的用法来看,yield 其实就是返回的意思。从逻辑上看,yield 跟 return 的行为也是类似的,都是结束当前函数执行,回到调用处并提供一个返回值。
所以 yield 的含义没有大家想的那么深奥,其实就是在 return 这个关键字被占用了的情况下,找了一个合适的近义词来表示生成器里这种特殊的“返回”而已。
相应的,如果我们要把 yield 翻译成中文的话,那也找一个比较合适的、与返回近义的词就行。如回归、交付之类的都可以。