Reassigning a Slice variable

The following works, but feels wrong somehow.

I have a [][]string Slice (below called “outer”).
In a loop, I want to calculate a []string Slice (below called “inner” and add it to the above “outer”.

Simplified code here:

package main
import "fmt"
func main() {
   var outer [][]string
   var inner []string
   inner = []string{}
   // The following is simplified: The population
   // of inner is in fact more than just assignments:
   inner = append(inner, aa, bb, cc)
   outer = append(outer, inner)
   inner = []string{ba, bb, bc}
   outer = append(outer, inner)
   inner = []string{ca, cb, cc, cd}
   outer = append(outer, inner)
   fmt.Println(outer)
}

Perhaps I am a confused about the “pointer nature” of Slices in some context, i.e. that they are passed by reference (with fixed headers / cap, though).

Question:
What happens to the Array under the “inner” Slice? Is a new Array created every time I reassign “inner” to a new value?
Is that expensive?
The only alternative I see is sizing the Slices (not so easy because I don’t know the required caps when starting the loop) and then assigning individual fields like:

outer[0][0] = “aa”

Hi! Since you don’t have any information about caps, you have to append the inner slice every time, and in your code inner is allocated each time you want to overwrite it. A better solution could be controlling if the number of element of the new inner is greater than the last inner cap and eventually allocate a new slice; what you’re always doing instead. Consider the second case (we call it Case 2):
you assign the new elements to inner range, from index 0 to new required cap…and return a new slice from the just overwritten inner slice (an efficient operation), which you append to outer than. In this way you save all the allocations related to new required caps less or equal than old inner cap, and continue to append to outer only the slices you want.
Tell me if you don’t understand :slight_smile:

Thank you. No worries: Your proposed solutions sound clear to me.
Where the new “inner” has less elements than the one in the previous iteration, I will just need to cut off inner’s “heritage” slice element(s).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.