How to split a slice in Go in sub-slices

10,753

Solution 1

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]

Solution 2

my_sub_slice1 := my_slice[0:2]
my_sub_slice2 := my_slice[2:4]
my_sub_slice3 := my_slice[4:6]
Share:
10,753

Related videos on Youtube

claudioz
Author by

claudioz

Updated on June 04, 2022

Comments

  • claudioz
    claudioz almost 2 years

    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!

  • Mindaugas Jaraminas
    Mindaugas Jaraminas over 2 years
    This is a better approach.
  • Sergey
    Sergey over 2 years
    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]...)