3

I'm recently using Go to create applications. My question is this: at a certain point in the program I have a string slice:

my_slice = []string{"string1","string2","string3","string4","string5","string6"}

It contains 6 strings. Which is the best procedure (easier to write and understand) to break this slice into 3 parts, for example, and distribute the content in three sub-slices? If I have:

var my_sub_slice1 []string
var my_sub_slice2 []string
var my_sub_slice3 []string

I wish at the end of it my_sub_slice1 will contain (in his first two entries) "string1","string2"; my_sub_slice2 will contain (in his first two entries) "string3","string4"; my_sub_slice3 will contain (in his first two entries) "string5","string6". I know the question is easy but I haven't found a clean and efficient way to do this yet. Thanks a lot!

claudioz
  • 1,121
  • 4
  • 14
  • 25

2 Answers2

10

A general solution to split a slice to into sub-slices of equal length

s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
size := 2
var j int
for i := 0; i < len(s); i += size{
    j += size
    if j > len(s) {
        j = len(s)
    }
    // do what do you want to with the sub-slice, here just printing the sub-slices
    fmt.Println(s[i:j])
}

// output
// [1 2]
// [3 4]
// [5 6]
// [7 8]
// [9 10]
RANJITH R
  • 117
  • 1
  • 4
4
my_sub_slice1 := my_slice[0:2]
my_sub_slice2 := my_slice[2:4]
my_sub_slice3 := my_slice[4:6]
cd1
  • 15,908
  • 12
  • 46
  • 47
  • This is a better approach. – Mindaugas Jaraminas Jan 07 '22 at 07:56
  • 1
    Beware that modifying contents of any of my_sub_sliceX, you will ALSO modify contents of original my_slice. Because subslicing does not involve data copy. If you need to create separate copy of data, use `append`: my_sub_slice1 := append([]string{}, my_slice[0:2]...) – Sergey Jan 10 '22 at 11:19