有人问我关于在某些Go代码中发现错误,但对于这个明显的错误应该是什么我感到困惑。我被问到以下内容:
此代码有什么问题?它是不完整的,但该片段应足以发现该错误。您将如何解决?您还能提出什么其他改进?
尝试了不同的编码解决方案作为示例并找到了错误,但是在代码中看不到明显的错误,因为我可以使此代码正常工作(取决于我的编码方式)。我告诉他们代码在关闭通道之前没有等待工作进程,也没有检查它们是否已完成。我说过,代码太抽象了,不能肯定地说,它取决于代码的目标,但是可以使它工作正常(当然,不是那样的话)。
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).
*/
没有具体的预期输出,只是尝试查找此错误,以便在我进一步研究Go语言时可以从这个问题中学习。任何人都可以发现明显的错误并解释错误在哪里/什么地方?