Metaphysics of array, slice and append in go

Time:2021-7-22
func main() {
    Arr: = make ([] int, 0, 9) // length 0, capacity 9
    FMT. Printf ("address 0: P% n", ARR) // address unchanged
    FMT. Printf ("len: D, cap: D, data:% + V / N", len (ARR), cap (ARR), ARR) // length 0
    Arr = append (arr, 1, 2, 3) // the address remains unchanged, and the underlying array remains unchanged
    FMT. Printf ("len: D, cap: D, data:% + V / N", len (ARR), cap (ARR), ARR) // length 3
    Add (ARR) // append add
    fmt.Println(arr)
    FMT. Printf ("address 2: P / N", ARR) // the address remains unchanged, and the underlying array remains unchanged
    //Length 3, length unchanged, value unchanged: 1, 2, 3
    fmt.Printf("len: %d, cap: %d, data:%+v \n", len(arr), cap(arr), arr)
}

func add(arr []int) {

    //Append only changes the len length of the parameter, and does not change the len length of the original value, but the underlying array value changes and the address remains unchanged
    //However, modifying the original data (arr [1] = 10, arr [2] = 11) can change the original slice, which is a reference type
    //In addition, we should also pay attention to the change of the underlying array after the automatic expansion when the cap capacity is insufficient
    arr = append(arr, 10, 11)
    FMT. Printf ("address 1% P / N", ARR) // address unchanged, underlying array unchanged
    FMT. Printf ("len:% D, cap:% D, data:% + V \ n", len (ARR), cap (ARR), ARR) // length 5, values: 1, 2, 3, 10, 11
}

go

This work adoptsCC agreementReprint must indicate the author and the link of this article

Everything is self-taught