golang, gouroutines, How to set up chanel in another chanel, and than read it after closing mother chanel

Issue

I’m rather new in Golang, but working hard on understanding this great language! Please, help me in this..

I have 2 chanels. “In” and “Out” chanels

    in, out := make(chan Work), make(chan Work)

I set up goroutines workers that are listening for in chanel, grab work and do it. I have some work, that i would send into In chanel.

When Work is done by worker, it writes to the Out chanel.

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()
}

When all work is done I close both chanels at the write time of the program.

Now I want to write the results of done work in OUT chanel, but to separate all in some parts, for example, if work type would be like this :

type Work struct {
    Date string
    WorkType string
    Filters []Filter
}

if WorkType is “firstType” I would like to send the done work to one chanel, and if WorkType is “secondType” to second chan… But there might be over 20 types of work .. How to resolve this case in a better way?

Can I set up chanels in chanel OUT, and grab data from this sub chanels?

p.s.: Forgive me my noob questions, please..

Solution

You can have the output channel be generic, and handle different work items using a type switch.

Say your output channel is just chan interface{}.

The consumer of ready work items will look something like:

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!")
   }
}

and the handlers handle a specific type, i.e.

func handleTypeOne(w workTypeOne) { 
    ....
}

Answered By – Not_a_Golfer

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.