Go language trivia append () function

Source: Internet
Author: User

The built-in append () function appends an item to slice. If the slice also has free capacity (Cap (s) > len (s)), it is appended directly. Otherwise, the slice is expanded before being appended. These are detailed in the documentation for the Append () function, but the document does not say how the expansion is done, so the following is an experiment with a piece of code:

Package Main

func main () {
    s: = []int{}; println (Cap (s))//0
    s = Appendn (s, 1); println (Cap (s))//2
    s = APPENDN (S, 2); println (Cap (s))//4
    s = Appendn (S, 4), println (Cap (s))//8
    s = APPENDN (S, 8); println (Cap (s))//+
    s = AppE NdN (S, 16);  println (Cap (s))//+
    s = Appendn (s, +), println (Cap (s))//
    s = Appendn (s, +), println (Cap (s))//
    s = []int{1,2,3}; println (Cap (s))//3
    s = Appendn (S, 2), println (Cap (s))//8
}

func appendn (s []int, n int) []int {
    fo R I: = 0; I < n; i++ {
        s = append (s, 0)
    }
    return s
}

It can be seen that, at least for the above code, the capacity is not simply growing enough to accommodate the new item each time it needs to be scaled up, but is further expanded to 2n

Related Article

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.