Append function usage analysis in Go language _golang

Source: Internet
Author: User

This article analyzes the use of append function in Go language. Share to everyone for your reference. Specifically as follows:

The append in the go language is powerful and can be used to make many features more concise. The following is a simple comparison:

Inserts a slice into another slice at the specified location:

Do not use append:

Copy Code code as follows:
Func Insertsliceatindex (Slice_origin []int, Slice_to_insert []int,
Insertindex int) (result []int, err Error) {
If Insertindex > Len (slice_origin) {
return nil, errors. New ("Insertindex cannot be greater than slice_origin length")
}

result = Make ([]int, Len (slice_origin) +len (Slice_to_insert))
For I: = 0; I < Len (result); i++ {
If I < Insertindex {//insertion point
Result[i] = Slice_origin[i]
else If I < Insertindex+len (Slice_to_insert) {//insert Content
Result[i] = Slice_to_insert[i-insertindex]
} else {
Result[i] = Slice_origin[i-len (Slice_to_insert)]
}
}
Return
}

When you use append, the code is very concise:

Copy Code code as follows:
D: = []string{"Welcome", "for", "Tianjin", "Have", "a", "good", "Journey"}
Insertslice: = []string{' It ', ' is ', ' a ', ' big ', ' City '}
Insertsliceindex: = 3
D = Append (D[:insertsliceindex],
Append (Insertslice, D[insertsliceindex:] ...) ...)
Fmt. Printf ("result:%v\n", D)

I hope this article will help you with your go language program.

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.