Go language Learning Note 11: slicing (slice)

Source: Internet
Author: User
Go language Learning Note 11: slicing (slice)

The concept of slicing I learned from the Python language when I felt that it was really useful. It's not as tedious to write as the Java language. But I think the future Java syntax will also support.

Defining slices

Slices can be defined using the Make function, or you can create a slice of an unspecified size like a variable declaration.

var x []int = make([]int, 3);y := make([]int, 3);z := []int {1, 2, 3};

Make has three parameters, the first of which is the type (array type, so with square brackets), the second is the length Len, and the third is the capacity cap. The length is good to understand, is the value of how much. And the capacity is not good understanding, capacity is designed to reduce the number of automatic expansion, in order to reduce the number of expansion, you can come up on a larger set.

Slicing operations
s := arr[:]s := arr[1:2]s := arr[1:]s := arr[:2]
Len () and Cap () functions

This two function in order to get the slices of Len and cap.

Empty (nil) slices

A slice defaults to nil before being initialized, with a length of 0.

Append () and copy () functions

Append is to add elements to the original slice. Copy is a duplicate of the original slice, if not copied, then modify the new slice content, the original corresponding elements will also be modified.

var x []intx = append(x, 1);x = append(x, 2, 3, 4);y := make([]int, len(x), cap(x) * 2)copy(y, x);

Go language Learning Note 11: slicing (slice)

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.