切片是由数组建立的一种方便、灵活且功能强大的包装(Wrapper)。切片本身不拥有任何数据。它们只是对现有数组的引用。
package main import "fmt" func main(){ var a = [8]int{1,2,3,4,5,6} var b = a[1:5] fmt.Println(b) // 打印结果:[2 3 4 5] }
package main import "fmt" func main(){ var a = [8]int{1,2,3,4,5,6} a[2] = 50 fmt.Println(a) // 打印结果:[1 2 50 4 5 6 0 0] }
package main import "fmt" func main(){ var a [9]int = [9]int{1,2,3,4,5,6} var b []int = a[2:5] fmt.Println(len(b)) // 索引2:5的值为3位,所以打印结果为3 fmt.Println(cap(b)) // 容量是从索引第二位开始,索引打印结果为7 }
package main import "fmt" func main(){ var a[]int = make([]int,3) fmt.Println(a) }
package main import "fmt" func main(){ var a [8]int = [8]int{1,2,3,4,5,6} var b[]int = a[2:6] b = append(b,666) fmt.Println(b) // 打印结果:[3 4 5 6 666] 直接在切片值得后面追加值 }
package main import "fmt" func main(){ var b =make([]int,3,4) test(b) fmt.Println(b) } func test(b []int) { b[0]=999 fmt.Println(b) }
type slice struct { Length int Capacity int ZerothElement *byte }
package main import "fmt" func main(){ var a[][]string = make([][]string,2,3) fmt.Println(a[0]) if a[0] == nil{ fmt.Println("空") } }
package main import "fmt" func main(){ var a=make([]int,3,100) a[0] = 66 a[1] = 99 fmt.Println(a) var b =make([]int,3,4) fmt.Println(b) copy(b,a) //b复制a的值 fmt.Println(b) }