Go Append function and write

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

Slice

There are two kinds of initialization methods for slices, one is literal initialization and the other is make
It is not recommended to use new
When adding a member, the capacity is 2 exponential, 2,4,8,16,32. It also increases capacity when the length exceeds the capacity.

Append function

append(type,len,cap)该函数第一个参数是类型,第二个参数是分配的空间,第三个参数是预留分配空间
a:=make([]int, 5, 10)a[4]// 正确a[5]//报错

This is because the space reserved by the CAP needs to be re-sliced before it can be used, such as reallocating space when dynamically appending.
You can also manually assign

func main(){    a := make([]int, 10, 20)    fmt.Println(a)    b := a[:cap(a)]    fmt.Println(b)}//[0 0 0 0 0 0 0 0 0 0]//[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

is to append an element to the end of the array, which is the built-in function of go.
When we append an element to a slice with append, go will create a new tile variable if the capacity is not enough
Therefore the append is dynamically increased. There is no need to worry about the error of index out of range.

var s []string s= append(s ,"last")

Append is more appropriate for the initial slice of the literal.
Since make has passed in the initial size, we are actually getting an empty element with this size number of slice types. The use of append at this point is appended after the empty element.

func main(){    var s=make([]string,10);    s=append(s,"last");    print(s)}// ["0","0","0","0","0","0","0","0","0","0","last"]

If you want to continue using make to initialize, then you need to use the third parameter, "Cap"

func main(){    var s=make([]string,0,10);    s=append(s,"last");    print(s)}// ["last"]

Append Limitations

But there are limitations, such as not being used in

type mystruct{mystring string }type mystruct2{mystring2 string }var a []mystructvar b []mystruct2for _, item := range b{    b=append(a.mystring,item.mystring2)}

and want to be able to give the object array of sub-properties, according to the original order of the array to add (so also can not directly turn a into a map traversal, unless in some order to reorder), think of one method is to use the direct assignment expression

for index, item := range b{   a[index].mystring=item.mystring2}

However, this will cause an error, indicating index out of range. Because the a declaration is the default initialization length of 0.
Instead--

var b []mystruct2a := make([]mystruct,len(b))for index, item := range b{   a[index].mystring=item.mystring2}

This will solve the problem.
Also, if you need to filter the required data in a loop, Len (b) is the length of all the data in the B array. When the slice gives the initial size, it is actually an empty element that contains the slice type of this size number.
So there is no assigned part, still "empty".

// a=[{"A"},{"B"},{"C"},{"D"}]var b []mystruct2a := make([]mystruct,len(b))for index, item := range b{if(index/2!=0){//奇数index   a[index].mystring=item.mystring2   }}//a=[{"A"},{},{"C"},{}]

When you do some operations on a (such as flipping) there will be some empty data, the first element will not be taken.
Such as

//a=[{"A"},{},{"C"},{}]func InvertedOrder(arr []mystruct)([]mystruc){    for from , to := 0 , len(arr) -1 ; from < to ; from , to = from + 1, to -1{        arr[from] , arr[to] = arr[to] , arr[from]    }    return arr}a_invert := InvertedOrder(a)//a=[{},{"C"},{},{"A"}]

One way to compare low is to count and then re-slice

var countfor index, item := range b{if(index/2!=0){//奇数index    count++   a[count-1].mystring=item.mystring2   }}a=a[:count]

Did not think of other better methods, initialize the capacity of the slice is not to be shrunk, not used

Reference

Https://studygolang.com/artic ...

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.