Analysis of some basic problems of go slice

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
    • About Golang's slice I think is one of the features of go, it fully improved the array of several limited places, this article simple analysis of slice use process you will encounter several problems:

Let's look at the following example:

sliceA:=[]int{1,2,3}sliceB:=sliceA[0:2]sliceA[0]=4fmt.Println(sliceB)//此处输出什么?

The above code shows that slice's assignment operation is a reference type (address copy) that changes itself after the original slice is affected. Then if you want to not be affected, you can choose the copy operation:

sliceA:=[]int{1,2,3}sliceB:=make([]int,len(sliceA))copy(sliceA,sliceB)

Note the copy operation requires that the address space be created first for the operand.

Let's look at the following questions:

sliceA:=[]int{1,2,3}sliceB:=append(sliceA,4,5)sliceC:=sliceB[0:3]fmt.Println(len(sliceA),len(sliceB),len(sliceC))//输出什么?fmt.Println(cap(sliceA),cap(sliceB),cap(sliceC))//输出什么?

Correct result:

3 5 33 6 6

Analysis above you can know, append operation slice the underlying array capacity will multiply, Len is slice length, that is, the actual value of the length, cap is the capacity of the request. The concept of capacity in go needs to be thought about. The
SLICEC is assigned a value equal to SLICEB, but with a different length.

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.