Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Array and slice examples in Go language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the Go language array and slice case analysis related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this Go language array and slice case analysis article, let's take a look.

1. Array

An array is a sequence of fixed-length elements of a particular type, and an array can consist of zero or more elements. Because arrays are fixed in length, arrays are rarely used directly in the Go language. The type corresponding to the array is Slice, which is a dynamic sequence that can grow and contract, and the slice function is more flexible.

Each element of the array can be accessed through an index subscript, which ranges from 0 to the length of the array minus 1. The built-in len function returns the number of elements in the array.

Var a [3] int / / array of 3 integersfmt.Println (a [0]) / / print the first elementfmt.Println (a [len (a)-1]) / / print the last element, a [2]

By default, each element of the array is initialized to a zero value for the element type, which is 0 for the numeric type.

Var Q [3] int = [3] int {1,2,3} var r [3] int = [3] int {1,2} fmt.Println (r [2]) / / "0"

If "..." appears at the length of the array. An ellipsis indicates that the length of the array is calculated based on the number of initialization values. Therefore, the definition of the above Q array can be simplified to:

Q: = [...] int {1,2,3} fmt.Printf ("% T", Q) / / "[3] int"

The length of an array is an integral part of the array type, so [3] int and [4] int are two different array types.

The length of the array must be a constant expression because the length of the array needs to be determined at compile time.

Q: = [3] int {1,2,3} Q = [4] int {1,2,3,4} / / compile error: cannot assign [4] int to [3] int

If the element types of an array can be compared with each other, then the array types can also be compared with each other, so we can compare the two arrays directly through the = = comparison operator. the array is equal only if all the elements of the two arrays are equal. The unequal comparison operator! = follows the same rules.

A: = [2] int {1,2} b: = [...] int {1,2} c: = [2] int {1,3} fmt.Println (a = = b, a = = c, b = = c) / / "true false false" d: = [3] int {1,2} fmt.Println (a = = d) / / compile error: cannot compare [2] int = = [3] int2. Slice (Slice)

Slice (slice) represents a sequence of varying lengths, and each element in the sequence has the same type. A slice type is generally written as [] T, where T represents the type of element in slice; the syntax of slice is very similar to an array, except that it has no fixed length.

A slice is a lightweight data structure that provides access to array subsequence (or all) elements, and the underlying slice does reference an array object.

A slice consists of three parts: pointer, length, and capacity.

The pointer points to the address of the underlying array element corresponding to the first slice element, noting that the first element of slice is not necessarily the first element of the array.

The length corresponds to the number of elements in the slice

The length cannot exceed the capacity, which is generally from the beginning of the slice to the end of the underlying data. The built-in len and cap functions return the length and capacity of the slice, respectively.

An array of strings representing the names of each month of the year, as well as two slice that overlap the array. The array is defined as follows:

Months: = [...] string {1: "January", / *... * /, 12: "December"}

So January is months, December is months.

Usually, the first element of an array starts at index 0, but the month usually starts at 1, so when we declare the array, we skip the 0 element directly, and the 0 element is automatically initialized to an empty string.

Slice's slicing operation s [i≤ j], where 0 ≤ I ≤ j ≤ cap (s) is used to create a new slice, referencing the subsequence of s starting from the first element to the first element. The new slice will have only JMII elements. If the index of I position is omitted, 0 will be used instead, and if the index of j position is omitted, len (s) will be used instead. Therefore, the months [1:13] slicing operation references all valid months, which is equivalent to the months [1:] operation; the months [:] slicing operation references the entire array. Let's define the slice for the second quarter and the northern summer month, respectively, which overlap:

Q2: = months [4:7] summer: = months [6:9] fmt.Println (Q2) / / ["April"May"June"] fmt.Println (summer) / / ["June"July"August"]

Both slice include June.

Append function

The append function is used to append elements to slice:

Var runes [] runefor _, r: = range "Hello, World" {runes = append (runes, r)} fmt.Printf ("% Q", runes) / / "[" H "" e "" l "" l "" o "," World "and" World "]"

To improve memory efficiency, the newly allocated array is generally slightly larger than the minimum size required to save x and y. It avoids multiple memory allocations by directly doubling the length of the array each time you expand the array, and ensures that the average time of adding a single element operation is a constant time. This program demonstrates the effect:

Func main () {var x, y [] int for i: = 0; I < 10 Fmt.Printf + {y = appendInt (x, I) fmt.Printf ("% d cap=%d% v", I, cap (y) Y) x = y}} / / each change in capacity results in reallocation of memory and copy operations: 0 cap=1 [0] 1 cap=2 [0 1] 2 cap=4 [0 1 2 3] 3 cap=4 [0 1 2 3 4] 4 cap=8 [0 1 2 3 4] 5 cap=8 [0 1 2 3 4 5] 6 cap=8 [0 1 2 3 4 5 6] 7 cap=8 [0 1 2 3 4 5 6 7] 8 cap=16 [0 1 2 3 4 5 6 7 8] 9 cap=16 [0 1 2 3 4 5 6 7 8 9]

Let's take a closer look at the three iterations of iTunes. At that time, x contained [0 1 2] three elements, but the capacity was 4, so you could simply add new elements to the end without new memory allocation. Then the new y has a length and capacity of 4 and references the same underlying array as x, as shown in figure 4.2.

In the next iteration, iTun4, there is no new free space now, so the appendInt function allocates an underlying array with a capacity of 8, copies the four elements of x [0 1 2 3] to the beginning of the new space, and then adds a new element I with a value of 4. The new y has a length of 5 and a capacity of 8; there are three free locations behind, and no new space needs to be allocated for three iterations. In the current iteration, y and x are view corresponding to different underlying arrays. This operation is shown in figure 4.3.

The built-in append function may use a more complex memory expansion strategy than appendInt.

Therefore, we usually don't know if the append call results in memory reallocation, so we can't confirm that the new slice and the original slice refer to the same underlying array space.

Again, we cannot confirm whether the operation on the original slice will affect the new slice.

This is the end of the article on "Array and slice example Analysis in Go language". Thank you for reading! I believe you all have a certain understanding of the knowledge of "array and slice case analysis in Go language". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report