Arrays 如何判断append是否创建了新的基础数组

Arrays 如何判断append是否创建了新的基础数组,arrays,go,slice,Arrays,Go,Slice,是否可以判断追加内置函数是否创建了一个新的基础阵列?当然,比较之前和之后的容量: before := cap(myArray) myArray = append(myArray, newValue) after := cap(myArray) fmt.Printf("before: %d, after: %d", before, after) 更好的问题是,你为什么需要这样做?您的代码实际上不应该关心是否创建了新的备份数组 操场演示:您可以查找第一个元素的内存指针 如果按照两个步骤的功率放大内

是否可以判断追加内置函数是否创建了一个新的基础阵列?

当然,比较之前和之后的容量:

before := cap(myArray)
myArray = append(myArray, newValue)
after := cap(myArray)
fmt.Printf("before: %d, after: %d", before, after)
更好的问题是,你为什么需要这样做?您的代码实际上不应该关心是否创建了新的备份数组


操场演示:

您可以查找第一个元素的内存指针

如果按照两个步骤的功率放大内部容量,则会发生变化

package main

import (
    "fmt"
)

func main() {
    sl := make([]int, 0, 4)
    sl = append(sl, []int{1,2}...)  
    fmt.Printf("%#v<-%v # same pointer address to the slice length 2 with capacity 4\n", &sl[0], len(sl))
    sl = append(sl, []int{1,2}...)  
    fmt.Printf("%#v<-%v # same pointer address to the slice length 2 with capacity 4\ncapacity will change from the next append on:\n", &sl[0], len(sl))
    for i:=0; i<10; i++{
        sl = append(sl, 1)
        fmt.Printf("%#v<-len(%v) cap(%v)\n", &sl[0], len(sl), cap(sl))
    }
    for i:=0; i<10; i++{
        sl = append(sl, sl...)
        fmt.Printf("%#v<-len(%v) cap(%v)\n", &sl[0], len(sl), cap(sl))
    }
}

will print:
(*int)(0x414020)<-2 # same pointer address to the slice length 2 with capacity 4
(*int)(0x414020)<-4 # same pointer address to the slice length 2 with capacity 4
capacity will change from the next append on:
(*int)(0x450020)<-len(5) cap(8)
(*int)(0x450020)<-len(6) cap(8)
(*int)(0x450020)<-len(7) cap(8)
(*int)(0x450020)<-len(8) cap(8)
(*int)(0x432080)<-len(9) cap(16)
(*int)(0x432080)<-len(10) cap(16)
(*int)(0x432080)<-len(11) cap(16)
(*int)(0x432080)<-len(12) cap(16)
(*int)(0x432080)<-len(13) cap(16)
(*int)(0x432080)<-len(14) cap(16)
(*int)(0x456000)<-len(28) cap(32)
(*int)(0x458000)<-len(56) cap(64)
(*int)(0x45a000)<-len(112) cap(128)
(*int)(0x45c000)<-len(224) cap(256)
(*int)(0x45e000)<-len(448) cap(512)
(*int)(0x460000)<-len(896) cap(1024)
(*int)(0x462000)<-len(1792) cap(2048)
(*int)(0x464000)<-len(3584) cap(4096)
(*int)(0x468000)<-len(7168) cap(8192)
(*int)(0x470000)<-len(14336) cap(16384)

注意:如果查看指向切片的不安全指针,出于好奇,变化模式不太明显

,为什么?我喜欢在学习一门新语言的时候尽我所能地玩弄各种东西,这有助于我学得更好、更好faster@icza感谢您提供的源代码,尽管我很清楚何时分配新阵列以及如何使用内置的容量参数,这并不是我想问的——只是想知道如何判断是否发生了。也许作为围棋候选人的面试问题?@aryzing答案包含信息,可以告诉你何时分配了新的支持阵列。确实是个好问题,但不是我要问的问题;B/c我喜欢在学习一门语言的过程中玩弄它的深远影响,在面试过程中,观察应聘者的反应可能是一个有趣的问题。