这是我的代码:
package main
import "fmt"
func main() {
numList := make([]int, 4)
numList[0] = 1
numList[1] = 2
numList[2] = 3
numList[3] = 4
fmt.Println(numList)
numList = append(numList[1:2])
fmt.Println("numList: ", numList)
numList = append(numList[0:])
fmt.Println(numList)
numList2 := append(numList[0:2])
fmt.Println(numList2)
numList3 := append(numList[0:3])
fmt.Println(numList3)
numList4 := append(numList[0:4])
fmt.Println(numList4)
}
输出为:
[1 2 3 4] // EXPECTED
numList: [2] //EXPECTED
[2] // EXPECTED
[2 3]
[2 3 4]
panic: runtime error: slice bounds out of range [:4] with capacity 3
输出的最后三行非常令人困惑。
numList = append(numList[1:2])
和 numList = append(numList[0:])
给出 [2]
。numList2 := append(numList[0:2])
如何将输出提供为 [2 3]
和 numList3 := append(numList[0:3])
如何将输出提供为 [2 3 4]
? 3和4是从哪里来的?
有人可以解释一下这里到底发生了什么吗?
我将逐步解释发生了什么:
// 1. Initial creation and assignments
numList := make([]int, 4) // [0 0 0 0] len=4, cap=4
numList[0] = 1 // [1 0 0 0]
numList[1] = 2 // [1 2 0 0]
numList[2] = 3 // [1 2 3 0]
numList[3] = 4 // [1 2 3 4]
fmt.Println(numList) // Prints: [1 2 3 4]
// 2. First slice operation
numList[1:2] // Creates view: [2]
numList = append(numList[1:2])// New slice: [2] len=1, cap=3
// Underlying array: [2 3 4 ?]
fmt.Println("numList: ", numList) // Prints: [2]
// 3. Second slice operation
numList[0:] // Creates view: [2]
numList = append(numList[0:]) // Still: [2] len=1, cap=3
// Underlying array: [2 3 4 ?]
fmt.Println(numList) // Prints: [2]
// 4. Creating numList2
numList[0:2] // Even though len=1, can access up to cap=3
// Creates view: [2 3]
numList2 := append(numList[0:2]) // [2 3] len=2, cap=3
fmt.Println(numList2) // Prints: [2 3]
// 5. Creating numList3
numList[0:3] // Can access up to cap=3
// Creates view: [2 3 4]
numList3 := append(numList[0:3]) // [2 3 4] len=3, cap=3
fmt.Println(numList3) // Prints: [2 3 4]
// 6. Creating numList4 - PANIC!
numList[0:4] // Trying to access beyond cap=3
// PANIC: slice bounds out of range [:4] with capacity 3
numList4 := append(numList[0:4])
fmt.Println(numList4)
注意事项: