BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / golang / #966同步于 2017/12/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Golang机器人发帖

一个go语言slice相关的小白问题

bond1993
2017/12/18镜像同步3 回复
var s = make([]int, 8) for i:= range s{ s[i] = i } fmt.Println(s[1:3]) fmt.Println(s[1:3:8]) fmt.Println(s[:3:8]) fmt.Println(s[:3:10]) fmt.Println(s[1:3:5:7]) 分别输出: [1 2] [1 2] [0 1 2] panic 编译错误 第一行好理解,但是后三行的:8与:10有啥作用?matlab中类似语法是控制步长,但是这里不是,表面看起来没有起任何作用(除了产生错误)。 查了不少地方没找到这种用法的介绍。请大神指点。
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
Rvtea机器人#1 · 2017/12/27
``` package main import ( "fmt" ) func printSlice(s []int) { fmt.Printf("slice attributes: %d, %d\n", len(s), cap(s)) } func main() { var s = make([]int, 8) for i:= range s{ s[i] = i } s1 := s[1:3] s2 := s[1:3:8] s3 := s[:3:8] // same as s[0:3:8] //s4 := s[:3:10] // same as s[0:3:10], while 10 > cap(s) which is 8, should panic here. //s5 := s[1:3:5:7] // I don't know wtf is s[1:3:5:7]... if you know, please tell me... fmt.Println(s[1:3]) fmt.Println(s[1:3:8]) fmt.Println(s[:3:8]) //fmt.Println(s[:3:10]) //fmt.Println(s[1:3:5:7]) printSlice(s1) printSlice(s2) printSlice(s3) //printSlice(s4) //printSlice(s5) } ``` or try this https://play.golang.org/p/sss6YGiexA_g
bond1993机器人#2 · 2017/12/28
谢谢!! 竟然还有这种操作.jpg 【 在 Rvtea 的大作中提到: 】 : [md] : ``` : package main : ...................
limingji0503机器人#3 · 2018/7/23
s[1:3:8] 1,3,8 分别表示 元素下界索引,元素上界索引,容量上界索引 其中元素下界索引和容量上界索引是可以省略的。 楼上说的是对的,因为cap(s) = 8 < 10,所以fmt.Println(s[:3:10]) 会panic 【 在 bond1993 的大作中提到: 】 : var s = make([]int, 8) : for i:= range s{ : s[i] = i : ...................