Golang (Go language) Append function return value must have a variable to receive the reason to explore

Source: Internet
Author: User
The Append function returns the updated slice (length and capacity may change) and must be re-received with the slice variable, otherwise it cannot be compiled by trying to figure out why, first we need to clear a few things: the bottom of the slice is an array, a contiguous memory, and the slice variable simply stores the SL The start position, end position, and capacity of ice in the underlying array.
Its length can be calculated from the start position and end position, and the capacity can be calculated from the start position to the end position of the underlying array, and multiple slice can point to the same underlying array. So slice and array pointers are different, arrays pointers primarily store the first address of the underlying array.
Because the Go function pass is a value copy by default, passing the slice variable into the APPEND function is equivalent to passing a copy of the original slice variable, noting that the underlying array is not copied because the slice variable is not an array, it simply stores some information about the underlying array.
So, when it changes the information passed into the slice variable, the original slice variable does not change, and the original slice variable is printed exactly the same as before. The function returns the modified slice variable, because the original slice does not change, and if no slice variable receives the returned value, then this append operation is meaningless. So you have to have slice variable to re-receive the modified slice variable, or the compiler will error. Go does not want you to do meaningless things, like the imported package or the defined variables are not used, it will also error.
The individual understands this, and if there is something wrong, please correct me.
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.