So I am very new to go! But I had this idea about something I wanted to try.
I would like to have a go routine that accepts strings from a channel but only after it has received N strings should it execute on them.
I looked around for similar questions or cases but I only found ones where the idea was to execute several routines in parallel and wait to aggregate the result.
I though about the idea of creating an array and just pass it to a routine where the length was sufficient. However I want to keep a certain separation of concerns and control this on the receiving end.
My questions are.
- Is this bad practice for some reason?
-
Is there a better way to do this, what is it?
func main() { ch := make(chan string) go func() { tasks := []string{} for { tasks = append(tasks,<- ch) if len(tasks) < 3 { fmt.Println("Queue still to small") } if len(tasks) > 3 { for i := 0; i < len(tasks); i++ { fmt.Println(tasks[i]) } } } }() ch <- "Msg 1" time.Sleep(time.Second) ch <- "Msg 2" time.Sleep(time.Second) ch <- "Msg 3" time.Sleep(time.Second) ch <- "Msg 4" time.Sleep(time.Second) }
Edit for simpler more accurate example.