dpl3350 2015-01-14 07:55
浏览 372
已采纳

golang切片,用slice切片[a:b:c]

I read go slice usage and internals and Slice and Effective go#slice but there is nothing about slicing a slice with 3 number like this : slice[a:b:c]

For example this code :

package main

import "fmt"

func main() {
    var s = []string{"a", "b", "c", "d", "e", "f", "g"}
    fmt.Println(s[1:2:6], len(s[1:2:6]), cap(s[1:2:6]))
    fmt.Println(s[1:2:5], len(s[1:2:5]), cap(s[1:2:5]))
    fmt.Println(s[1:2], len(s[1:2]), cap(s[1:2]))

}

go playground result is this :

[b] 1 5
[b] 1 4
[b] 1 6

I can understand that the third one is something about capacity, but what is the exact meaning of this?
Do I miss something in documents?

  • 写回答

1条回答 默认 最新

  • dsfjk44656 2015-01-14 08:34
    关注

    The syntax has been introduced in Go 1.2, as I mentioned in "Re-slicing slices in Golang".
    It is documented in Full slice expressions:

    a[low : high : max]
    

    constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high].
    Additionally, it controls the resulting slice's capacity by setting it to max - low.
    Only the first index may be omitted; it defaults to 0.

    After slicing the array a:

    a := [5]int{1, 2, 3, 4, 5}
    t := a[1:3:5]
    

    the slice t has type []int, length 2, capacity 4, and elements

    t[0] == 2
    t[1] == 3
    

    The design document for that feature had the following justification:

    It would occasionally be useful, for example in custom []byte allocation managers, to be able to hand a slice to a caller and know that the caller cannot edit values beyond a given subrange of the true array.

    The addition of append to the language made this somewhat more important, because append lets programmers overwrite entries between len and cap without realizing it or even mentioning cap.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集