Considerations when creating slice with arrays in Golang

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

In Golang, Slice is a slice of a fixed-length array, and its underlying is implemented with pointers to numerical spaces.

In Golang when you use an array to create slice, such as:

array [5]int = [5]int{1,2,3,4,5}//切割出数组中的4个值,创建一个slicearray[0:4]

The value of the print array is:

1, 2, 3, 4, 5

The values for printing Mysqlice are:

1, 2, 3, 4

Now we're append the myslice operation.

myslice = append(myslice,100)

The value of the print array is:

1, 2, 3, 4, 100

The values for printing Mysqlice are:

1, 2, 3, 4, 100

Now we're going to modify the Myslice.

myslice[0] = 50

The value of the print array is:

50, 2, 3, 4, 100

The values for printing Mysqlice are:

50, 2, 3, 4, 100

When the length of the slice is not greater than the length of the array created, slice also points to the array that was used when it was created.

But!

The length of the Myslice is now consistent with the length of the array used to create the slice.
Let's append the Myslice to make the myslice longer than the length of the array used at the time of creation.

myslice = append(myslice,200)

The value of the print array is:

50, 2, 3, 4, 100

The values for printing Mysqlice are:

50, 2, 3, 4, 100, 200

Myslice is not associated with ARR in the way of pointers? For hair This situation has not changed the value of arr?

Because when the myslice exceeds the length of arr, the go language implicitly makes a copy of the array and myslice the internal pointer back to the new value, so everything expected to modify the value of the array will not take effect!

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.