Hello, I would like to know the best way to close a channel in a recursive function ?
Here is a typical example is a simple function to generate all possible 1-3 letter words :
package main
import "fmt"
func main() {
result := make(chan string)
go words(3, "", result)
for v := range result {
fmt.Printf("%s\n", v)
}
fmt.Println("got here")
}
func words(length int , prefix string, result chan string) {
if length < 1 {
return
}
letter := ""
for i := 97 ; i < 123 ; i++ {
letter = fmt.Sprintf("%s%c", prefix, i)
result <- letter
words(length - 1, letter , result)
}
}
- How do you effectively close result or is there a better way to achieve the same result ?
- What the best way to increase performance when working with eg go words(10, "", result) because go words(length - 1, letter , result) can lead to too many goroutines