make
slice := make([]int, 5) // 初始化长度和容量都为 5 的切片 slice := make([]int, 5, 10) // 初始化长度为 5, 容量为 10 的切片
slice := []int{1, 2, 3, 4, 5}
arr := [5]int{1, 2, 3, 4, 5} slice := arr[0:3] // 左闭右开区间,最终切片为 [1,2,3]
sliceA := []int{1, 2, 3, 4, 5} sliceB := sliceA[0:3] // 左闭右开区间,sliceB 最终为 [1,2,3]
package main import ( "fmt" ) func main() { slice := []int{1, 2, 3, 4, 5} fmt.Println("len: ", len(slice)) fmt.Println("cap: ", cap(slice)) //改变切片长度 slice = append(slice, 6) fmt.Println("after append operation: ") fmt.Println("len: ", len(slice)) fmt.Println("cap: ", cap(slice)) //注意,底层数组容量不够时,会重新分配数组空间,通常为两倍 }
以上代码,预期输出如下:
len: 5 cap: 5 after append operation: len: 6 cap: 12
对底层数组的修改,将影响上层多个切片的值
package main import ( "fmt" ) func main() { slice := []int{1, 2, 3, 4, 5} newSlice := slice[0:3] fmt.Println("before modifying underlying array:") fmt.Println("slice: ", slice) fmt.Println("newSlice: ", newSlice) fmt.Println() newSlice[0] = 6 fmt.Println("after modifying underlying array:") fmt.Println("slice: ", slice) fmt.Println("newSlice: ", newSlice) }
以上代码预期输出如下:
before modify underlying array: slice: [1 2 3 4 5] newSlice: [1 2 3] after modify underlying array: slice: [6 2 3 4 5] newSlice: [6 2 3]
copy
示例代码如下:
package main import ( "fmt" ) func main() { slice := []int{1, 2, 3, 4, 5} newSlice := make([]int, len(slice)) copy(newSlice, slice) fmt.Println("before modifying underlying array:") fmt.Println("slice: ", slice) fmt.Println("newSlice: ", newSlice) fmt.Println() newSlice[0] = 6 fmt.Println("after modifying underlying array:") fmt.Println("slice: ", slice) fmt.Println("newSlice: ", newSlice) }
before modifying underlying array: slice: [1 2 3 4 5] newSlice: [1 2 3 4 5] after modifying underlying array: slice: [1 2 3 4 5] newSlice: [6 2 3 4 5]
如何使用 copy 函数进行切片部分拷贝?
// 假设切片 slice 如下: slice := []int{1, 2, 3, 4, 5} // 如何使用 copy 创建切片 newSlice, 该切片值为 [2, 3, 4] newSlice = copy(?,?)
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8