数组
go
package main
import "fmt"
func main() {
//固定长度的数组
var myArray1 [10]int
//for i := 0; i < 10; i++ {
for i := 0; i < len(myArray1); i++ {
fmt.Println(myArray1[i])
}
// --------------------------------
myArray2 := [10]int{1,2,3,4}
// range 关键字,返回 index value 两个值
for index, value := range myArray2 {
fmt.Println("index = ", index, ", value = ", value)
}
//查看数组的数据类型
fmt.Printf("myArray1 types = %T\n", myArray1)
myArray3 := [4]int{11,22,33,44}
// 传递的是拷贝数组,所以不会改变原数组
printArray(myArray3)
}动态数组
动态数组传值传的是引用值
go
package main
import "fmt"
func printArray(myArray []int) {
//引用传递
// _ 表示匿名的变量
for _, value := range myArray {
fmt.Println("value = ", value)
}
myArray[0] = 100
}
func main() {
myArray := []int{1,2,3,4} // 动态数组,切片 slice
fmt.Printf("myArray type is %T\n", myArray)
printArray(myArray)
fmt.Println(" ==== ")
for _, value := range myArray {
fmt.Println("value = ", value)
}
}make
make([]int, 3)开辟3个空间
go
package main
import "fmt"
func main() {
//声明slice1是一个切片,并且初始化,默认值是1,2,3。 长度len是3
//slice1 := []int{1, 2, 3}
//声明slice1是一个切片,但是并没有给slice分配空间
var slice1 []int
//slice1 = make([]int, 3) //开辟3个空间 ,默认值是0
// 同上
//var slice1 []int = make([]int, 3)
// 同上
//slice1 := make([]int, 3)
fmt.Printf("len = %d, slice = %v\n", len(slice1), slice1)
//判断一个silce是否为0
if slice1 == nil {
fmt.Println("slice1 是一个空切片")
} else {
fmt.Println("slice1 是有空间的")
}
}append
向切片追加元素,返回新切片(需重新赋值):
go
numbers = append(numbers, 1) // 追加一个
numbers = append(numbers, 1, 2) // 追加多个len:当前元素个数,每次 append 后 +1cap:底层数组容量,len超过cap时自动扩容(通常翻倍)make([]int, 3, 5)指定 cap;make([]int, 3)未指定时 cap 等于 len
go
package main
import "fmt"
func main() {
// len=3, cap=5
numbers := make([]int, 3, 5)
printSlice("init", numbers)
numbers = append(numbers, 1, 2) // len=5, cap=5
printSlice("append 1,2", numbers)
numbers = append(numbers, 3) // cap 满了,自动扩容 cap=10
printSlice("append 3", numbers)
// 未指定 cap 时,cap 默认等于 len
numbers2 := make([]int, 3)
printSlice("numbers2 init", numbers2)
numbers2 = append(numbers2, 1) // cap 自动扩容为 6
printSlice("numbers2 append 1", numbers2)
}
func printSlice(label string, s []int) {
fmt.Printf("%s: len=%d, cap=%d, slice=%v\n", label, len(s), cap(s), s)
}运行结果:
sh
init: len=3, cap=5, slice=[0 0 0]
append 1,2: len=5, cap=5, slice=[0 0 0 1 2]
append 3: len=6, cap=10, slice=[0 0 0 1 2 3]
numbers2 init: len=3, cap=3, slice=[0 0 0]
numbers2 append 1: len=4, cap=6, slice=[0 0 0 1]slice
go
package main
import "fmt"
func main() {
s := []int{1, 2, 3} //len = 3, cap = 3, [1,2,3]
//[0, 2)
s1 := s[0:2] // [1, 2]
fmt.Println(s1)
//copy 可以将底层数组的slice一起进行拷贝
s2 := make([]int, 3) //s2 = [0,0,0]
//将s中的值 依次拷贝到s2中
copy(s2, s)
fmt.Println(s2)
/*创建切片*/
numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("numbers[1:4]--", numbers[1:4])
fmt.Println("numbers[:3] ==", numbers[:3])
fmt.Println("numbers[4:]=*", numbers[4:])
numbersl := make([]int, 0, 5)
/*打印子切片从索引0(包含)到索引2(不包含)*/
number2 := numbers[:2]
}