Home  >  Article  >  Backend Development  >  The difference between golang array and slice

The difference between golang array and slice

尚
Original
2019-12-31 14:11:412387browse

The difference between golang array and slice

Array refers to a series of collections of data of the same type. Each data contained in the array is called an array element. This type can be any primitive type, such as int, string, etc., or a user-defined type. The number of elements an array contains is called the length of the array.

In Golang, an array is a fixed-length data type, and the length of the array is part of the type.

Slice is a special data structure in Golang. This data structure is easier to use and manage data collections. Slices are built around the concept of dynamic arrays, which can automatically grow and shrink on demand.

Let’s take a look at the difference between arrays and slices in go language:

1. The definition methods are different

2. The initialization method is different:

The array needs to specify the size. If not specified, the size will be automatically calculated based on the initialization and cannot be changed.

The slice does not need to specify the size. .

3. Function transfer methods are different: arrays are transferred by value, and slices are transferred by address.

Array definition:

var a1 [3]int
var a2 [...]int{1,2,3}

Slice definition

var b1 []int
b2 := make([]int, 3, 5)

Array initialization

a1 := [...]int{1,2,3}
a2 := [5]int{1,2,3}

Slice initialization

b1 := make([]int, 3,5)

More For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of 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