英文:
Creating fixed length slices from slice
问题
我有一个整数切片,我需要将其切割成较小的切片,并使用这些新切片进行函数调用。我需要将每个新切片中放入5个对象。如果arr1
的长度可以被5整除,我可以实现一个正确工作的解决方案。然而,在其他情况下,我会遇到一个超出范围的错误,如panic: runtime error: slice bounds out of range [:26] with capacity 24
。我理解问题及其原因,我在最后一个循环中给出了错误的索引值,当arr1_len
不能被5整除时,我的逻辑失败了。我的问题是,我如何将arr1
切割成每个切片中有5个对象的新切片,除了最后一个切片可能少于5个对象?
英文:
I have a slice of integers which I need to cut into smaller slices and use these new slices to a function call. I have to put 5 objects into every new slice. I could implement a solution which works correctly if the length of the arr1
is dividable with 5
. However in other cases I will get an out of range error like this: panic: runtime error: slice bounds out of range [:26] with capacity 24
. I understand the problem and its cause, I give wrong index values at the last loop, my logic fails when arr1_len
can't be divided by 5. My question is that how could I slice arr1
into new slices with 5 objects in every slice, except the last one which can hold less than 5.? Playground link
package main
import "fmt"
func printRes(l []int) {
fmt.Println(l)
}
func sliceTest() {
arr1 := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}
arr1_len := len(arr1)
val := 5
val2 := 0
for i := 0; i <= arr1_len; i = i + val {
val2 = i + val
currentSlice := arr1[i:val2]
fmt.Println(i, val2, currentSlice)
printRes(currentSlice)
}
}
func main() {
sliceTest()
}
答案1
得分: 3
检查边界:
val2 = i + val
if val2 >= len(arr1):
val2 = len(arr1)
英文:
Check bounds:
val2 = i + val
if val2 >= len(arr1) {
val2 = len(arr1)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论