使用Go语言简单模拟Python的生成器
defdemo_input_and_output(): input=yield'whatistheinput?' yield'inputis:%s'%input gen=demo_input_and_output() print(gen.next()) print(gen.send(42))
这段代码演示了pythongenerator的功能。可以看到yield同时做了两个操作,一个是往外发数据"wahtistheinput",同时做的操作是往里收数据input。而且这个接收数据的操作是一个阻塞的操作,如果外部没有调用next()(也就是往里传递None),或者调用send(42)(也就是往里传递42这个值),那么这个阻塞的操作就会一直等待下去。
也就是说python的generator自带了一个对外通信的channel,用于收发消息。用go模拟python的generator的话写起来就是这样的
packagemain
import"fmt"
funcdemoInputAndOutput(channelchanstring){ channel<-"whatismyinput?" input:=<-channel channel<-fmt.Sprintf("inputis:%s",input) }
funcmain(){ channel:=make(chanstring) godemoInputAndOutput(channel) fmt.Println(<-channel) channel<-"42" fmt.Println(<-channel) }
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短