gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:08:10 28 4
gpt4 key购买 nike

我读了go slice usage and internalsSliceEffective go#slice但是没有像这样用 3 个数字 slice 的方法:slice[a:b:c]

例如这段代码:

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结果是这样的:

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

我能理解第三个是关于容量的东西,但是这个具体是什么意思呢?
我是否遗漏了文档中的某些内容?

最佳答案

语法已经在 Go 1.2 中引入,正如我在“Re-slicing slices in Golang”中提到的。
它记录在 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

design document该功能具有以下理由:

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.

关于golang slice,用 slice[a :b:c] slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938177/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com