Is it possible to leave a channel in Go open after a goroutine finishes?
Hello everyone! I'm a beginner Go developer and trying to understand channels. I have this code:\n\n```go\npackage main\n\nimport (\n\t"fmt"\n\t"time"\n)\n\nfunc worker(done chan bool) {\n\tfmt.Println("Working...")\n\ttime.Sleep(2 * time.Second)\n\tfmt.Println("Done!")\n\t// Here I don't close the channel\n\tdone <- true\n}\n\nfunc main() {\n\tdone := make(chan bool)\n\tgo worker(done)\n\n\t// Wait for the result\n\tresult := <-done\n\tfmt.Println("Result:", result)\n\n\t// What happens to the done channel? It remains open.\n\ttime.Sleep(1 * time.Second)\n\tfmt.Println("Program finished")\n}\n```\n\nThe code works, but I noticed that I never close the `done` channel. The documentation says that channels should be closed, but I don't understand if it's mandatory. In my example, the program terminates,
No answers yet.
Log in to leave an answer
Blogs