[Golang]也许有你不知道的,Array和Slice(1)


Golang中的array

    在golang中,array是同一类型的元素的有序排列,长度不能更改,占用内存上的一段连续空间。

    1)基础

    首先看看array的声明:
  1. var justiceArray [3]string  
var justiceArray [3]string
 以上声明了justiceArray是为有3个元素的string数组,括号里面的数字是必须的,不能省略。
    另外说明一下,[3]string与[2]string是两种不同类型的array。
    现在对其赋值:
  1. justiceArray = [3]string{"Superman", "Batman", "Wonder Woman"}  
  2. fmt.Printf("The Justice League are: %v\n", justiceArray)  
  3. 输出:  
  4. The Justice League are: [Superman Batman Wonder Woman]  
justiceArray = [3]string{"Superman", "Batman", "Wonder Woman"}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
    如果你只想创建一个填充默认值的数组,可以这样:
  1. justiceArray = [3]string{}  
  2. fmt.Printf("The Justice League are: %v\n", justiceArray)  
  3. 输出:  
  4. The Justice League are: [  ]  
justiceArray = [3]string{}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [  ]
    当前数组拥有3个空的字符串。
    另外你可以用一种省略形式:
  1. justiceArray = [...]string{"Superman", "Batman", "Wonder Woman"}  
  2. fmt.Printf("The Justice League are: %v\n", justiceArray)  
  3. 输出:  
  4. The Justice League are: [Superman Batman Wonder Woman]  
justiceArray = [...]string{"Superman", "Batman", "Wonder Woman"}
fmt.Printf("The Justice League are: %v\n", justiceArray)
输出:
The Justice League are: [Superman Batman Wonder Woman]
    用...代替数字,当然大括号里的元素需要跟你声明的数组长度一致。
    目的相同,下面这种声明赋值就更简洁了:

  1. avengersArray := [...]string{"Captain America", "Hulk"}  
  2. fmt.Printf("The Avengers are: %v\n", avengersArray)  
  3. 输出:  
  4. The Avengers are: [Captain America Hulk]  
avengersArray := [...]string{"Captain America", "Hulk"}
fmt.Printf("The Avengers are: %v\n", avengersArray)
输出:
The Avengers are: [Captain America Hulk]
  等号右边的返回类型是[2]string。

    2)数组的复制

    需要强调一点的是,array类型的变量指代整个数组变量(不同于c中的array,后者是一个指针,指向数组的第一元素);
  类似与int这些基本类型,当将array类型的变量赋值时,是复制整个数组,参照下面这个例子:

  1. newAvengers := avengersArray  
  2. newAvengers[0] = "Spider-Man"  
  3. fmt.Printf("The old avengers: %v\n", avengersArray)  
  4. fmt.Printf("The new avengers: %v\n", newAvengers)  
  5. 输出:  
  6. The old avengers: [Captain America Hulk]  
  7. The new avengers: [Spider-Man Hulk]  
newAvengers := avengersArray
newAvengers[0] = "Spider-Man"
fmt.Printf("The old avengers: %v\n", avengersArray)
fmt.Printf("The new avengers: %v\n", newAvengers)
输出:
The old avengers: [Captain America Hulk]
The new avengers: [Spider-Man Hulk]
    上面将avengersArray赋值给newAvengers时,是复制了整个数组,而不是单纯的指向。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值