Go语言中的切片,是一种动态数组,它是对数组的扩展。
2.1.1 声明⼀个未指定⻓度的数组来定义切⽚
2.1.2 使⽤make()函数来创建切⽚:
//mySlice.go
package main
import (
"fmt"
)
func main() {
//fmt.Println("Hello World!")
//1)切片
var numbers = make([]int, 3, 5)
fmt.Printf("%T\n", numbers)
fmt.Printf("len=%d cap=%d slice=%v\n", len(numbers), cap(numbers), numbers)
}
效果如下:
s :=[] int {1,2,3 }
数组: arr := [5]int {1,2,3,4,5}
可以通过设置下限及上限来设置截取切⽚ [lower-bound:upper-bound] 即前闭后开: [lower-bound, upper-bound)
//mySlice2.go
package main
import (
"fmt"
)
func printSlice(x []int) {
fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}
func main() {
//fmt.Println("Hello World!")
//1)切片
// var numbers = make([]int, 3, 5)
// fmt.Printf("%T\n", numbers)
// fmt.Printf("len=%d cap=%d slice=%v\n", len(numbers), cap(numbers), numbers)
//2)截取切片
numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
printSlice(numbers)
//打印原始切片
fmt.Println("numbers== ", numbers)
//打印子切片,从索引1到索引4,左闭右开,[1,4)
fmt.Println("numbers[1:4]== ", numbers[1:4])
//默认下限为0,[0,3)
fmt.Println("numbers[:3]== ", numbers[:3])
//默认上限为len(s),[4,len(s))
fmt.Println("numbers[4:]== ", numbers[4:])
//打印子切片,[0,2)
number2 := numbers[:2]
printSlice(number2)
//打印子切片,[2,5)
number3 := numbers[2:5]
printSlice(number3)
}
效果如下:
// mySliceCap project main.go
package main
import (
"fmt"
)
func main() {
sliceCap()
}
func sliceCap() {
arry := [...]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}
fmt.Println("cap(arry)= ", cap(arry), arry)
//截取数组,形成切片
sli01 := arry[2:8]
fmt.Printf("%T\n", sli01)
fmt.Println("cap(sli01)= ", cap(sli01), sli01)
sli02 := arry[4:7]
fmt.Println("cap(sli02)= ", cap(sli02), sli02)
//截取切片,形成切片
sli03 := sli01[3:9]
fmt.Println("截取sli01[3:9]后形成sli03: ", sli03)
sli04 := sli02[4:7]
fmt.Println("截取sli02[4:7]后形成sli04: ", sli04)
//切片是引用类型
sli04[0] = "x"
fmt.Print(arry, sli01, sli02, sli03, sli04)
}
运行结果如下:
修改数组的案例,如下:
//mySlice04.go
// mySliceCmp project main.go
package main
import (
"fmt"
)
func main() {
a := [4]float64{67.7, 89.8, 21, 78}
b := []int{2, 3, 5}
fmt.Printf("变量a -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &a, a, a, len(a))
fmt.Printf("变量b -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &b, b, b, len(b))
c := a
d := b
fmt.Printf("变量c -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &c, c, c, len(c))
fmt.Printf("变量d -- 地址: %p, 类型: %T, 数值: %v, 长度: %d\n", &d, d, d, len(d))
a[1] = 200
fmt.Println("a= ", a, " c= ", c)
d[0] = 100
fmt.Println("b= ", b, " d= ", d)
}
运行结果如下:
// mySliceChg project main.go
package main
import (
"fmt"
)
func main() {
//定义数组
arry := [3]int{1, 2, 3}
//根据数组截取切片
nums1 := arry[:]
nums2 := arry[:]
fmt.Println("arry= ", arry)
nums1[0] = 100
fmt.Println("arry= ", arry)
nums2[1] = 200
fmt.Println("arry= ", arry)
fmt.Printf("变量arry --地址: %p\n", &arry)
fmt.Printf("变量nums1 --地址: %p\n", &nums1)
fmt.Printf("变量nums2 --地址: %p\n", &nums2)
}
运行结果如下: