相关疑难解决方法(0)

在Golang中重新切片

我最近拿起了Go,现在我对以下代码感到困惑:

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)
    b := make([]int, 0, 5)
    printSlice("b", b)
    c := b[:2]
    printSlice("c", c)
    d := c[2:5]
    printSlice("d", d)
}

func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0] //why the capacity of c not 2 but 5 instead
d len=3 cap=3 [0 0 …
Run Code Online (Sandbox Code Playgroud)

arrays slice

18
推荐指数
2
解决办法
1万
查看次数

Golang的“帽子”

下面的go代码:

var numbers4 = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
slice := numbers4[4:6:8] 
fmt.Printf("%d\n", cap(slice))
Run Code Online (Sandbox Code Playgroud)

为什么cap(slice)等于4

我以前以为应该是这样2

arrays go slice

0
推荐指数
1
解决办法
1069
查看次数

标签 统计

arrays ×2

slice ×2

go ×1