The append of slice in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

In the Golang language, the data type is not many, but enough, the development project process, slice belongs to one of the most commonly used data structure, the understanding of its principle is not clear, it is easy to leave the bug, the author inquires a lot of blog material, to slice append principle to carry on a summary, If you do not know what to write, please forgive and correct it.

package mainimport "fmt"func main(){  s := []int{5}      s = append(s,7)  fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0])      s = append(s,9)  fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0])      x := append(s, 11)  fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(x) =", &x[0])      y := append(s, 12)  fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(y) =", &y[0])}

Output:

cap(s) = 2 ptr(s) = 0x10328008cap(s) = 4 ptr(s) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(x) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(y) = 0x103280f0

Actual process:

Text Description:

    1. When creating S, cap (s) = = 1, in-memory data [5]
    2. Append (S, 7), press slice expansion mechanism, cap (s) doubled = = 2, in-memory data [5,7]
    3. Append (S, 9), press slice expansion mechanism, cap (s) Doubles = = 4, in-memory data [5,7,9], but actual memory block capacity 4
    4. x: = Append (S, 11), sufficient capacity does not require expansion, in-memory data [5,7,9,11]
    5. Y: = Append (S, 12), sufficient capacity does not require expansion, in-memory data [5,7,9,12]

The Append in 5 is the addition of element 12 on the basis of S, which is actually = = = From the end of the S-slice to write = =, so it covers 11

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.