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...

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案