温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

go 的数组和切片

发布时间:2020-03-15 14:21:36 来源:网络 阅读:260 作者:水滴石川1 栏目:编程语言

什么是数组?

数组

数组是一个由固定长度的特定类型元素组成的序列,一个数组可以由零个或多个元素组成

数组定义的方法?

方式一

package main
import "fmt"

func arraytest()  {
    var x [3] int
    fmt.Println(x) 
}
// 输出 [0 0 0]
func main()  {
    arraytest()
    }

使用快速声明数组

x3 :=[3] int {112,78}
fmt.Println(x3) 
输出 [112 78 0]

// 数组值的获取

var x2[3] int
    x2[0] = 1 //第一个元素
    x2[1] = 11
    x2[2] = 22 
    fmt.Println(x2) 
输出 [1 11 22]

// 使用for 循环获取数组的数据

 x6 :=[...] int {3,5,6,82,34}
    for i :=0; i< len(x6);i++{
        fmt.Println(i,x6[i])
    }
    // 输出   如下 0 表示索引号, 3表示 对应的具体值
 0 3
 1 5
 2 6
 3 82
 4 34

// go 语言中提供使用range 的方式获取

for i,v := range x6{
fmt.Printf("%d of x6 is %d\n",i,v)
}
// 输出 
0 3
1 5
2 6
3 82
4 34

// 只访问元素

for _,v1 :=range x6 {
    fmt.Printf("x6 array value is %d\n",v1)
}
// 输出

0 of x6 is 3
1 of x6 is 5
2 of x6 is 6
3 of x6 is 82
4 of x6 is 34

切片

什么是切片(slice)?

切片(slice)是 Golang 中一种比较特殊的数据结构,这种数据结构更便于使用和管理数据集合

// 切片的定义

package main
import "fmt"

func slicetest() {
a1 :=[4] int {1,3,7,22}
fmt.Println(a1)

// 输出

[1 3 7 22]
var b1 []int = a1[1:4]
fmt.Println(b1,len(b1)) 

// 输出

[3 7 22] 3

}

func main() {
slicetest()
}

// 使用make 声明切片
make 初始化函数切片的时候,如果不指明其容量,那么他就会和长度一致,如果在初始化的时候指明了其容量

 s1 :=make([]int, 5) 
    fmt.Printf("The length of s1: %d\n",len(s1)) # 长度
    fmt.Printf("The capacity of; s1: %d\n",cap(s1)) # cap 容量
    fmt.Printf("The value of s1:%d\n",s1)
    // 输出 

    The length of s1: 5
The capacity of; s1: 5
The value of s1:[0 0 0 0 0]

    s12 :=make([]int, 5,8) # 指明长度为 5, 容量为8
    fmt.Printf("The length of s12: %d\n",len(s12))
    fmt.Printf("The capacity of; s12: %d\n",cap(s12))
    fmt.Printf("The value of s12:%d\n",s12)
    // 输出

    The length of s12: 5
The capacity of; s12: 8
The value of s12:[0 0 0 0 0]

// 
s3 := []int{1, 2, 3, 4, 5, 6, 7, 8}
s4 := s3[3:6]
fmt.Printf("The length of s4: %d\n", len(s4))
fmt.Printf("The capacity of s4: %d\n", cap(s4))
fmt.Printf("The value of s4: %d\n", s4)

// 输出

The length of s4: 3  # 长度为3 
The capacity of s4: 5 # 容量为5  
The value of s4: [4 5 6]  

// 切片与数组的关系

切片的容量可以看成是底层数组元素的个数
s4 是通过s3 切片获得来的,所以s3 的底层数组就是s4 的底层数组,切片是无法向左拓展的,所以s4 无法看到s3 最左边的三个元素,所以s4 的容量为5

// 切片的获取

before_slice :=[] int {1,4,5,23,13,313,63,23}
after_slice := before_slice[3:7]

fmt.Println("array before change",before_slice)

// 使用for range 遍历

for i := range after_slice{
    after_slice[i]++
}
fmt.Println("after cahnge",before_slice)

// 输出

array before change [1 4 5 23 13 313 63 23]
after cahnge [1 4 5 24 14 314 64 23]

数组和切片的区别

容量是否可伸缩 ? 数组容量不可以伸缩,切片可以

是否可以进行比较? // 相同长度的数组可以进行比较

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI