Home > Backend Development > Golang > How to assign length to slice in golang

How to assign length to slice in golang

Release: 2020-01-14 10:00:43
Original
3032 people have browsed it

How to assign length to slice in golang

There are two concepts in slices: one is the len length, and the other is the cap capacity. The length refers to the maximum subscript 1 that has been assigned a value. It can be used through the built-in function len() get. Capacity refers to the maximum number of elements that the slice can currently hold, which can be obtained through the built-in function cap().

Slices can be initialized through arrays or through the built-in function make(). When initializing, len=cap. When appending elements, if the capacity cap is insufficient, the capacity will be expanded by 2 times of len.

s :=[] int {1,2,3 }
Copy after login

Directly initialize the slice, [] indicates the slice type, {1,2,3} initialization value is 1,2,3 in order. Its cap=len=3

s := arr[:]
Copy after login

Initialize the slice s, is a reference to the array arr

s := arr[startIndex:endIndex]
Copy after login

Create the elements in arr from subscript startIndex to endIndex-1 as a new slice

For more golang knowledge, please pay attention to PHP Chinese websitegolang tutorial column.

The above is the detailed content of How to assign length to slice in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template