Home  >  Article  >  Backend Development  >  How to determine whether a variable is a slice or an array in Go language

How to determine whether a variable is a slice or an array in Go language

藏色散人
藏色散人Original
2021-01-05 15:50:213457browse

Go language method to determine whether a variable is a slice or an array: 1. Determine whether the length of the variable cannot be modified when it is determined. If it cannot be changed, it means that the variable is an array array; 2. Define a length in brackets Value, with length value is array array, without length value is slice slice.

How to determine whether a variable is a slice or an array in Go language

The operating environment of this tutorial: Windows 7 system, Go1.11.2 version, Dell G3 computer.

Recommended: "go Language Tutorial"

Determine whether a variable is an array or a slice in golang

Array The difference between Slice and Slice

The biggest difference between the two is that once the array length is determined, it cannot be modified, cannot be lengthened, or cannot be shortened. Slicing scales capacity. And the array is a value type, when assigning one array to another array, a value copy occurs, while the slice is a pointer type, and the pointer is copied.

The following is explained through an example:

The code is as shown below, (1) defines a [3]int type array, and assigns values ​​​​to 1, 2, and 3 in sequence. (2) Assign array a to b, and value copying will occur. (3) Assigning a value of 4 to the element at subscript 2 of array a will not affect the contents of array b. (4) Print the results to explain the situation.

I am looking at another piece of code: (1) do not specify the length, (2) print the result, showing that the modification of a affects the content of b.

#Why does a subtle change make such a difference? This is the subtle difference in syntax when defining Array and Slice:

Defining a length value in parentheses is the only basis for the compiler to distinguish the data type of variable a,With the length value it is an array, without it it is a slice.

Back to the question, how to distinguish the following variables:

var a1 []int ---> No length definition, it is Slice

var a2 [ 2]int ---> There is a length definition, which is Array

var a3 [3]*int---> There is a length definition, which is Array

var a4 [4][ 3]int ---> It has a length definition and is an Array, which is just a two-dimensional array.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to determine whether a variable is a slice or an array in Go language. 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