我在戈朗是个新手,但在理解这门伟大的语言方面我很努力!拜托,帮帮我..。
我有两个念珠。"In“和"Out”
in, out := make(chan Work), make(chan Work)我在香奈儿成立了一家名叫戈鲁蒂的工人,他们在听着,抓住工作,然后去做。我有一些工作,我会派去香奈儿的。
当工作是由工人完成,它写到外面香奈儿。
func worker(in <-chan Work, out chan<- Work, wg *sync.WaitGroup) {
for w := range in {
// do some work with the Work
time.Sleep(time.Duration(w.Z))
out <- w
}
wg.Done()
}当所有的工作完成后,我会在程序编写的时候关闭两个循环。
现在,我想用chanel编写完成工作的结果,但是将所有的部分分开,例如,如果work类型是这样的话:
type Work struct {
Date string
WorkType string
Filters []Filter
}如果WorkType是"firstType“,我想把已经完成的作品寄给香奈儿,如果WorkType是"secondType”的话,我想把它寄给第二位陈.但可能有超过20种类型的工作。如何更好地解决这一问题?
我能不能在香奈儿外面建个教堂,然后从这个小教堂里获取数据?
请原谅我的问题。
发布于 2016-02-07 15:46:56
可以让输出通道是泛型的,并使用类型开关处理不同的工作项。
假设您的输出通道是chan interface{}。
现成工作项的使用者将类似于:
for item := range output {
// in each case statement x will have the appropriate type
switch x := item.(type) {
case workTypeOne:
handleTypeOne(x)
case workTypeTwo:
handleTypeTwo(x)
// and so on...
// and in case someone sent a non-work-item down the chan
default:
panic("Invalid type for work item!")
}
}处理程序处理特定类型,即
func handleTypeOne(w workTypeOne) {
....
}https://stackoverflow.com/questions/35254979
复制相似问题