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

What is the difference between golang array and slice?

青灯夜游
青灯夜游Original
2019-12-25 18:02:463449browse

What is the difference between golang array and slice?

The difference between arrays and slices in golang:

● Slices are pointer types, arrays are value types

● Arrays The length is fixed, but slices are not (slices are dynamic arrays)

● Slices have one more attribute than arrays: capacity (cap)

● The bottom layer of slices is arrays

Related recommendations: golang tutorial

Since one is a pointer type and the other is a value type, where is the difference?

Look at this example

	numbers := []int{1, 2, 3, 4, 5, 6}
	for i, e := range numbers {
		if i == len(numbers)-1 {
			numbers[0] += e
		} else {
			numbers[i+1] += e
		}
	}
	fmt.Println(numbers)

The result is:

[22 3 6 10 15 21]

Replace the slice with an array:

	numbers := [...]int{1, 2, 3, 4, 5, 6}
	for i, e := range numbers {
		if i == len(numbers)-1 {
			numbers[0] += e
		} else {
			numbers[i+1] += e
		}
	}
	fmt.Println(numbers)

The result is:

[7 3 5 7 9 11]

It’s obvious: after traversing, each element in the array becomes the sum of the current element and the previous element; the same is true for slicing, except that each element becomes the changed value of the previous element and the sum of the current element. and.

Analysis: During the for loop, the elements in numbers are {1,2,3,4,5,6}. The variables that receive the for loop are i and e, and i are both [0,1,2,3,4,5]. But e is different, the array is passed by value, so when traversing the array, e is {1,2,3,4,5,6}; slicing passes a pointer, so every time it is accumulated, the changed value is accumulated.

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
Previous article:What language is golang?Next article:What language is golang?