dongzhanlu0658 2018-06-06 06:35
浏览 18
已采纳

延长长度并保持价值

I follow the tour of Go to learning GOLANG.

And I have a question at this step: https://tour.golang.org/moretypes/11

  package main

  import "fmt"

  func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Step1 Slice the slice to give it zero length.
    s = s[:0]
    printSlice(s)

    // Step2 Extend its length.
    // Why after extend the length of the slice, the value in this slice is still  [2 3 5 7]
    s = s[:4]
    printSlice(s)

    // Step 3 Drop its first two values.
    s = s[2:]
    printSlice(s)
  }

  func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v
", len(s), cap(s), s)
  }

The output:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

Why after extending the length of the slice at the second step, the value in this slice is still [2 3 5 7]? I think the value in this slice is [0 0 0 0] because I have sliced the origin slice at the first step.

And I have another question is that why the third step can change the capacity of the slice but the first second cannot.

  • 写回答

1条回答 默认 最新

  • dongwu9063 2018-06-06 07:08
    关注

    Because the first time extending does not change the slice's pointer address. So s also points to the [2 3 5 7 11 13] address.

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        s := []int{2, 3, 5, 7, 11, 13}
        printSlice(s)
    
        // Slice the slice to give it zero length.
        s = s[:0]
        printSlice(s)
    
        // Extend its length.
        s = s[:4]
        printSlice(s)
    
        // Drop its first two values.
        s = s[2:]
        printSlice(s)
    }
    
    func printSlice(s []int) {
        fmt.Printf("len=%d cap=%d %v array ptr: %v 
    ", len(s), cap(s), s,(*unsafe.Pointer)(unsafe.Pointer(&s)))
    }
    

    the terminal shows:

    len=6 cap=6 [2 3 5 7 11 13] array ptr: 0xc04200a2a0
    len=0 cap=6 [] array ptr: 0xc04200a2a0
    len=4 cap=6 [2 3 5 7] array ptr: 0xc04200a2a0
    len=2 cap=4 [5 7] array ptr: 0xc04200a2b0
    

    you see, the third step changes the ptr address because of first item is changed. so you know...

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

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源