title: The idiomatic way to implement generators (yield) in Golang for recursive functions
body: <p>[ Note: I read <a href="https://stackoverflow.com/q/11385556/142239">Python-style generators in Go</a>, this is not a duplicate of it. ]</p>
  
  <p>In Python / Ruby / JavaScript / ECMAScript 6, generator functions could be written using the <code>yield</code> keyword provided by the language. In Go, it could be simulated using a goroutine and a channel.</p>
  
  <h1>The Code</h1>
  
  <p>The following code shows how a permutation function (abcd, abdc, acbd, acdb, ..., dcba) could be implemented:</p>
  
  <pre class="lang-golang prettyprint-override"><code>// $src/lib/lib.go
  
  package lib
  
  // private, starts with lowercase "p"
  func permutateWithChannel(channel chan&lt;- []string, strings, prefix []string) {
      length := len(strings)
      if length == 0 {
          // Base case
          channel &lt;- prefix
          return
      }
      // Recursive case
      newStrings := make([]string, 0, length-1)
      for i, s := range strings {
          // Remove strings[i] and assign the result to newStringI
          // Append strings[i] to newPrefixI
          // Call the recursive case
          newStringsI := append(newStrings, strings[:i]...)
          newStringsI = append(newStringsI, strings[i+1:]...)
          newPrefixI := append(prefix, s)
          permutateWithChannel(channel, newStringsI, newPrefixI)
      }
  }
  
  // public, starts with uppercase "P"
  func PermutateWithChannel(strings []string) chan []string {
      channel := make(chan []string)
      prefix := make([]string, 0, len(strings))
      go func() {
          permutateWithChannel(channel, strings, prefix)
          close(channel)
      }()
      return channel
  }
  </code></pre>
  
  <p>Here is how it could be used:</p>
  
  <pre class="lang-golang prettyprint-override"><code>// $src/main.go
  
  package main
  
  import (
      "./lib"
      "fmt"
  )
  
  var (
      fruits  = []string{"apple", "banana", "cherry", "durian"}
      banned = "durian"
  )
  
  func main() {
      channel := lib.PermutateWithChannel(fruits)
      for myFruits := range channel {
          fmt.Println(myFruits)
          if myFruits[0] == banned {
              close(channel)
              //break
          }
      }
  }
  </code></pre>
  
  <p>Note:</p>
  
  <p>The <code>break</code> statement (commented above) is not needed, as <code>close(channel)</code> causes <code>range</code> to return <code>false</code> in the next iteration, the loop will terminate.</p>
  
  <h1>The Problem</h1>
  
  <p>If the caller doesn't need all the permutations, it needs to <code>close()</code> the channel explicitly, or the channel will not be closed until the program terminates (resource leakage occurs). On the other hand, if the caller needs all the permutations (i.e. the <code>range</code> loops until the end), the caller MUST NOT <code>close()</code> the channel. It is because <code>close()</code>-ing an already closed channel causes a runtime panic (see <a href="https://golang.org/ref/spec#Close" rel="noreferrer">here in the spec</a>). However, if the logic to determine whether it should stop or not is not as simple as shown above, I think it is better to use <code>defer close(channel)</code>.</p>
  
  <h1>The Questions</h1>
  
  <ol>
  <li>What is the idiomatic way to implement generators like this?</li>
  <li>Idiomatically, who should be responsible to <code>close()</code> the channel - the library function or the caller?</li>
  <li>Is it a good idea to modify my code like below, so that the caller is responsible to <code>defer close()</code> the channel no matter what?</li>
  </ol>
  
  <p>In the library, modify this:</p>
  
  <pre class="lang-golang prettyprint-override"><code>    go func() {
          permutateWithChannel(channel, strings, prefix)
          close(channel)
      }()
  </code></pre>
  
  <p>to this:</p>
  
  <pre class="lang-golang prettyprint-override"><code>    go permutateWithChannel(channel, strings, prefix)
  </code></pre>
  
  <p>In the caller, modify this:</p>
  
  <pre class="lang-golang prettyprint-override"><code>func main() {
      channel := lib.PermutateWithChannel(fruits)
      for myFruits := range channel {
          fmt.Println(myFruits)
          if myFruits[0] == banned {
              close(channel)
          }
      }
  }
  </code></pre>
  
  <p>to this:</p>
  
  <pre class="lang-golang prettyprint-override"><code>func main() {
      channel := lib.PermutateWithChannel(fruits)
      defer close(channel)    // &lt;- Added
      for myFruits := range channel {
          fmt.Println(myFruits)
          if myFruits[0] == banned {
              break           // &lt;- Changed
          }
      }
  }
  </code></pre>
  
  <ol start="4">
  <li>Despite it is not observable by executing the code above, and the correctness of the algorithm is not affected, after the caller <code>close()</code>s the channel, the goroutine running the library code should <code>panic</code> when it tries to send to the closed channel in the next iteration, as documented <a href="https://golang.org/ref/spec#Send_statements" rel="noreferrer">here in the spec</a>, causing it to terminate. Does this cause any negative side-effect?</li>
  <li>The signature of the library function is <code>func(strings []string) chan []string</code>. Ideally, the return type should be <code>&lt;-chan []string</code> to restrict it to be receive-only. However, if it is the caller who is responsible to <code>close()</code> the channel, it could not be marked as "receive-only", as the <code>close()</code> built-in function does not work on receive-only channels. What is the idiomatic way to deal with this?</li>
  </ol>