title: Memory leak in golang slice
body: <p>I just started learning go, while going through slice tricks, couple of points are very confusing. can any one help me to clarify.</p>
  
  <p>To cut elements in slice its given </p>
  
  <p>Approach 1:</p>
  
  <pre><code>a = append(a[:i], a[j:]...)
  </code></pre>
  
  <p>but there is a note given that it may cause to memory leaks if pointers are used and recommended way is</p>
  
  <p>Approach 2:</p>
  
  <pre><code>copy(a[i:], a[j:])
  for k, n := len(a)-j+i, len(a); k &lt; n; k++ {
      a[k] = nil // or the zero value of T
  }
  a = a[:len(a)-j+i]
  </code></pre>
  
  <p>Can any one help me understand how memory leaks happen.
  I understood sub slice will be backed by the main array. My thought is irrespective of pointer or not we have to follow approach 2 always.</p>
  
  <p><strong>update after @icza and @Volker answer..</strong></p>
  
  <p>Lets say you have a struct </p>
  
  <pre><code>type Books struct {
      title   string
      author  string
  }
  
  var Book1 Books
  var Book2 Books 
  
      /* book 1 specification */
      Book1.title = "Go Programming"
      Book1.author = "Mahesh Kumar"
  
      Book2.title = "Go Programming"
      Book2.author = "Mahesh Kumar"
  
      var bkSlice = []Books{Book1, Book2}
      var bkprtSlice = []*Books{&amp;Book1, &amp;Book2}
  </code></pre>
  
  <p>now doing </p>
  
  <pre><code>bkSlice = bkSlice[:1]
  </code></pre>
  
  <p>bkSlice still holds the Book2 in backing array which is still in memory and is not required to be.
  so do we need to do</p>
  
  <pre><code>bkSlice[1] = Books{}
  </code></pre>
  
  <p>so that it will be GCed. I understood pointers have to be nil-ed as the slice will hold unnecessary references to the objects outside backing array.</p>