I was asked about finding a bug in some Go code and I am stumped as to what this obvious bug should be. I was asked the following:
What is wrong with this code? It’s incomplete, but the snippet should be enough to spot the bug. How would you fix it? What other improvements can you propose?
Tried different coding solutions to example and find the bug, but don't see an obvious bug in the code because I can get this code to work fine (depending on how I code for it). I told them that the code isn't waiting on the worker processes or checking that they're completing before closing the channel. I stated that the code is too abstract to say for sure and it depends on the goal of the code, but that it can be made to work fine (not that I'd code it that way, of course).
const nworkers = 5
type Task struct {
...
}
func worker(queue chan *Task) {
for task := range queue {
task.execute()
}
}
func main() {
tasks := getTasks()
queue := make(chan *Task, nworkers)
for i := 0; i < nworkers; i++ {
go worker(queue)
}
for i := 0; i < len(tasks); i++ {
queue <- tasks[i]
}
close(queue)
}
/*
Again, I had created some code to populate the missing code areas and
added wait to the workers and checks to ensure they completed, passing
the structure to the function call, added code to populate the struct
data and passed the data with queue <- &tasks[i] to reference (in how I
was doing it with one example) and so on. I literally can't see anything
obvious as per the bug in the code example if I fill in some blanks to
make it work).
*/
No specific expected output, just trying to locate this bug so I can learn from this question as I delve further into the Go language. Can anyone spot what should be an obvious bug and explain where/what the bug is?