E
E
Eugene2020-03-22 00:12:08
go
Eugene, 2020-03-22 00:12:08

How to split a slice into parts?

I have a slice that contains an arbitrary number of elements. You need to break it into parts of 1000 elements. For example, in a slice of 9600 elements, you should get 9 slices of 1000 and 1 of 600.
How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2020-03-22
@you_are_enot

// Подготовка исходного слайса
sourceSize := 9600
source := make([]int, sourceSize)
for i := 0; i < sourceSize; i++ {
  source[i] = i+1
}

// Разбиение слайса
chunkSize := 1000
result := make([][]int, 0)
var first, last int
for i := 0; i < len(source) / chunkSize + 1; i++ {
  first = i * chunkSize
  last = i * chunkSize + chunkSize
  if last > len(source) {
    last = len(source)
  }
  if first == last {
    break
  }

  result = append(result, source[first:last])
}

// Вывод результата
for _, res := range result {
  fmt.Println(res)
}

https://play.golang.org/p/FkaaZwLa53q

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question