我是 Golang 的新手,但正在努力理解這種偉大的語言!請幫我解決這個..我有2個香奈兒?!拜斎搿焙汀拜敵觥蓖ǖ?nbsp; in, out := make(chan Work), make(chan Work)我設(shè)置了在 chanel 中監(jiān)聽的 goroutines 工人,抓住工作并去做。我有一些工作,我會發(fā)送到香奈兒。當(dāng)工作由工人完成時,它會寫入 Out 通道。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()}完成所有工作后,我會在編寫程序時關(guān)閉兩個通道。現(xiàn)在我想在 OUT chanel 中寫完成工作的結(jié)果,但在某些部分將所有內(nèi)容分開,例如,如果工作類型是這樣的:type Work struct { Date string WorkType string Filters []Filter}如果 WorkType 是“firstType”,我想將完成的工作發(fā)送到一個 chanel,如果 WorkType 是“secondType”到第二個 chan...但可能有 20 多種類型的工作..如何更好地解決這種情況道路?我可以在 chanel OUT 中設(shè)置 chanels 并從該子 chanels 中獲取數(shù)據(jù)嗎?ps:請原諒我的菜鳥問題,請..
1 回答

墨色風(fēng)雨
TA貢獻(xiàn)1853條經(jīng)驗 獲得超6個贊
您可以讓輸出通道通用,并使用類型開關(guān)處理不同的工作項。
假設(shè)您的輸出通道只是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) {
....
}
- 1 回答
- 0 關(guān)注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消