首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Go语言编程17课:切片,步入数组的窗口

本课涵盖:

? 使用切片通过窗口查看太阳系

? 用标准库按字母顺序排列切片

太阳系中的行星被分类为类地行星、气态巨星和冰巨星。读者可以用planets[0:4]切割planets数组中的前4个元素,以主要关注类地行星。 切割不会改变planets数组,它只是在数组中创建一个窗口或视图。这个视图是一种称为切片的类型。

图17.1切割太阳系

考虑这一点

如果你有一个收藏集合,它以特定方式组织起来了吗? 图书馆书架上的书可以按照作者的姓氏排序。 这使你可以专注于同一个作家写的其他书籍。

切片可以用于以相同的方式对部分集合进行归零。

17.1切割一个数组

切片以半开区间表示。 例如,在以下列表中,planets[0:4]从planets于索引0开始继续往上到4,但不包括索引为4的行星。

程序清单17.1 切片数组:slicing.go

planets := [...]string{

"Mercury",

"Venus",

"Earth",

"Mars",

"Jupiter",

"Saturn",

"Uranus",

"Neptune",

}

terrestrial := planets[0:4]

gasGiants := planets[4:6]

iceGiants := planets[6:8]

fmt.Println(terrestrial, gasGiants, iceGiants)?

Print [Mercury Venus Earth Mars] [Jupiter Saturn] [Uranus Neptune]

虽然terrestrial,gasGiants和iceGiants都是切片,但你仍然可以像数组一样,在切片内索引。

fmt.Println(gasGiants [0])?????????????????????

Print Jupiter

读者也可以先切割数组,然后再切生成的切片。

giants := planets[4:8]

gas := giants[0:2]

ice := giants[2:4]

fmt.Println(giants, gas, ice) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

Print [Jupiter Saturn Uranus Neptune] [Jupiter Saturn] [Uranus Neptune]

terrestrial, gasGiants, iceGiants, giants, gas, and ice切片都是同一planets数组的视图。 为切片的元素分配新值实际上会修改潜在的planets数组。 更改将通过其他切片显示。

iceGiantsMarkII := iceGiants ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

iceGiants[1] = "Poseidon"

fmt.Println(planets)???????????????????????????????????????????????????????????????????????????? ?

fmt.Println(iceGiants, iceGiantsMarkII, ice) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

Copy the iceGiants slice (a view of the planets array)

Print [Mercury Venus Earth Mars Jupiter Saturn Uranus Poseidon]

Print [Uranus Poseidon] [Uranus Poseidon] [Uranus Poseidon]

快速检查

Q17.1当切割一个数组后产生了什么?

Q17.2用planets[4:6]切片后,结果中有多少元素?

17.1.1 切片的默认索引

切割一个数组时,省略第一个索引默认为数组的开头。省略最后一个索引默认为数组的长度。 这使得程序清单17.1中的切片可以写成如下形式。

程序清单17.2 默认索引:slicing-default.go

terrestrial := planets[:4]

gasGiants := planets[4:6]

iceGiants := planets[6:]

切片索引不能是负数。

读者大概可以猜到省略两个索引的用处。allPlanets变量是包含所有八大行星的切片。

allPlanets := planets[:]

切割字符串

数组的切片语法也适用于字符串。

neptune := "Neptune"

tune := neptune[3:]

fmt.Println(tune)

Print tune

切割字符串的结果会得到另一个字符串。然而,给neptune分配一个新的值不会改变tune的值,反之亦然。

neptune = "Poseidon" fmt.Println(tune)

Print tune

pdf百度云:

链接:https://pan.baidu.com/s/1yW7_zCS9BiR381FcGNPzfA 密码:6los

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180629A05YW900?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券
http://www.vxiaotou.com