Golang Slice Create

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

There are two ways to create a slice

Test: = []int{2,3}

Or use make, and we usually create more cases using made

For example:

Test: = Make ([]int, 5, 5)//Create a slice of type int, length 5, 5 capacity

Fmt. Println (len (test), Cap (test))//5 5

Test1: = Make ([]int, 3)//If no capacity is specified, the default capacity equals the initial length

Fmt. Println (Len (test1), Cap (test1))//3 3

The length and capacity of slice can be dynamically changed, slice is actually a part of the array

Test: = Make ([]int,0)//Create an array with a length of 0 and a capacity of 0

Fmt. Println (len (test), Cap (test))//0 0

Test = append (test, 1)

Fmt. Println (len (test), Cap (test))//1 1

Test = append (test, 1)

Fmt. Println (len (test), Cap (test))//2 2

Test = append (test, 1)

Fmt. Println (len (test), Cap (test))//3 4

When the capacity of the array is not enough, it will re-request a slice twice the current length, so in the process of use, especially frequent to a slice to append data, need to give as much as possible to a relatively accurate capacity, reduce the loss of the distribution process.


RELATED links:

Copy and append of slices

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.