go 数组、切片

时间:2023-03-09 18:54:05
go 数组、切片
  • 数组定义
    
    // 标准
var a []int = []int{, , , , }
fmt.Println("a", a) // 自动推导类型
b := []int{, , , , }
fmt.Println("b", b) // 其他默认为0
c := []int{, }
fmt.Println("c", c) // 指定部分下标值
d := []int{: , : }
fmt.Println("d", d) //a [5 4 4 3 2]
//b [5 4 2 3 2]
//c [3 5 0 0 0]
//d [0 0 10 0 9]
  • 切片定义
  • func createSlice() {
    //方式1 自动推导类型
    s1 := []int{, , , }
    fmt.Println(s1)
    //[1 2 3 4] //方式2 make函数 make(type,len,cap)
    s2 := make([]int, , )
    fmt.Println("s2=====", s2)
    fmt.Println("len(s)=", len(s2))
    fmt.Println("cap(s)=", cap(s2))
    //s2===== [0 0 0 0 0]
    //len(s)= 5
    //cap(s)= 10 // 不写cap,则cap=len
    s3 := make([]int, )
    fmt.Println("s2=====", s3)
    fmt.Println("len(s)=", len(s3))
    fmt.Println("cap(s)=", cap(s3))
    //s2===== [0 0 0 0 0]
    //len(s)= 5
    //cap(s)= 5
    }