Answer the question
In order to leave comments, you need to log in
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
// Подготовка исходного слайса
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)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question