Home  >  Article  >  Backend Development  >  What is the difference between golang array and slice

What is the difference between golang array and slice

silencement
silencementOriginal
2019-12-25 14:02:454060browse

What is the difference between golang array and slice

Array

is a built-in type, which is a collection of data of the same type. It is a value type. A subscript index starting from 0 accesses the element value. The length is fixed after initialization and

cannot modify its length. When passed as a parameter to a method, a copy of the array will be copied instead of referencing the same pointer. The length of an array is also part of its type, and its length can be obtained through the built-in function

len(array).

Note: Compared with arrays in C, there are some differences

1. Arrays in Go are value types. In other words, if you Assigning one array to another array is actually copying the entire array

2. If the array in Go is used as a parameter of the function, then the actual parameter passed is an array. A copy of the array, rather than a pointer to the array. This should be distinguished from C. Therefore, in Go

, if you pass an array as a parameter of a function, the efficiency is definitely not as high as passing a pointer.

3. The length of array is also part of Type, which means [10]int and [20]int are different.

Recommended to study "golang tutorial"

Slice

The length of the array cannot be changed, such a collection in a specific scenario It is not very applicable. Go provides a flexible and powerful built-in type Slices ("dynamic array"). Compared with the

array, the length of the slice is not fixed, and elements can be appended. When appending, the capacity of the slice may increase. There are two concepts in slicing: one is the length of len, and the other is the cap capacity. The length refers to the maximum subscript 1 that has been assigned a value, which can be obtained through the built-in function len(). Capacity refers to the maximum number of elements that a slice can currently hold, which can be obtained through the built-in function

cap(). Slices are reference types, so when passing a slice you will refer to the same pointer, and changing the value will affect other objects.

The above is the detailed content of What is the difference between golang array and slice. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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