1. Array
Arrays are a basic data type in Golang that is used to store a fixed number of elements of the same type. In Golang, the length of the array is fixed and must be specified when defining the array.
1.1 Defining an array
In Golang, you can declare an array using the following syntax:
var array name [array length] data type
For example, to declare an array of 5 integers, you can use the following code:
var arr [5]int
The above code defines an array called arr containing 5 integer elements. Elements in an array can be initialized using the following methods:
arr := [5]int{1, 2, 3, 4, 5}
The above code defines an array called arr that contains 5 integer elements. The values of elements are 1, 2, 3, 4 and 5, respectively.
We can also initialize an array during declaration by providing values for its elements. For example, to initialize an array of 3 strings, you can use the following code:
var names [3]string = [3]string{"Alice", "Bob", "Charlie"}
1.2 Accessing the array
An index operator ([]) can be used to access elements in an array. The index of the first element in the array is 0, and the index of the last element is length -1. For example, elements in an array can be accessed using the following methods:
arr := [5]int{1, 2, 3, 4, 5} (arr[0]) // Output 1 (arr[1]) // Output 2 (arr[2]) // Output 3
The above code outputs the first three elements in the array.
1.3 Modify the array
The elements in the array can be modified using the following methods:
arr := [5]int{1, 2, 3, 4, 5} arr[0] = 10 (arr) // Output [10 2 3 4 5]
The above code changes the first element in the array to 10 and outputs the modified array.
1.4 Array length
In Golang, you can use the len function to get the length of the array. For example, the following code gets the length of the array arr:
arr := [5]int{1, 2, 3, 4, 5} length := len(arr) (length) // Output 5
1.5 traverse array
You can use for loop to loop over elements in an array. For example, the following code traverses elements in the array arr:
arr := [5]int{1, 2, 3, 4, 5} for i := 0; i lt; len(arr); i++ { (arr[i]) }
The above code outputs all elements in the array.
1.6 Multidimensional array
Golang also supports multi-dimensional arrays. Here is an example of defining and initializing a two-dimensional array:
var arr [3][3]int arr = [3][3]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, } (arr)
The above code defines a 3x3 2D array and initializes all elements in the array. Elements in an array can be accessed using the following methods:
(arr[0][0]) // Output 1 (arr[0][1]) // Output 2 (arr[1][0]) // Output 4 (arr[2][2]) // Output 9
Arrays are very useful when we know the number of elements to store and do not need to change the size of the array at runtime. However, when we need a more flexible data type to change its size dynamically, we need to use slicing.
2. Slice
Slicing is a flexible data structure in Golang for processing sets of variable length elements. A slice is composed of an underlying array, length and capacity. The length of the slice indicates the number of elements in the slice, and the capacity indicates the number of elements in the underlying array referenced by the slice.
2.1 Defining slices
Slicing is a dynamic data structure built on an array. Slices can be declared using the following syntax:
var slice name [] data type
For example, to declare an integer slice, you can use the following code:
var slice []int
The above code defines a slice called slice that does not contain any elements.
Elements in a slice can be initialized using the following methods:
slice := []int{1, 2, 3, 4, 5}
The above code defines a slice called slice containing 5 integer elements. The values of elements are 1, 2, 3, 4 and 5, respectively.
2.2 Accessing slice elements
Elements in a slice can be accessed using the following methods:
slice := []int{1, 2, 3, 4, 5} (slice[0]) // Output 1 (slice[1]) // Output 2 (slice[2]) // Output 3
The above code outputs the first three elements in the slice.
2.3 Modify slice elements
Elements in a slice can be modified using the following methods:
slice := []int{1, 2, 3, 4, 5} slice[0] = 10 (slice) // Output [10 2 3 4 5]
The above code changes the first element in the slice to 10 and outputs the modified slice.
2.4 Slice length and capacity
You can use the len function to get the length of the slice and the cap function to get the capacity of the slice. For example, the following code gets the length and capacity of the slice slice:
slice := []int{1, 2, 3, 4, 5} length := len(slice) capacity := cap(slice) (length) // Output 5 (capacity) // Output 5
Note that the capacity here is equal to the length, because we do not specify the length of the underlying array.
2.5 Add elements to slices
You can use the append function to add elements to the slice. For example, the following code adds an element 6 to the slice slice:
slice := []int{1, 2, 3, 4, 5} slice = append(slice, 6) (slice) // Output [1 2 3 4 5 6]
The above code adds 6 to the end of the slice.
We can also add multiple elements to the slice at once. For example, to add integers 7, 8, and 9 to a "slice" slice, you can use the following code:
slice = append(slice, 7, 8, 9)
2.6 Slice slices
Since the slice is dynamic, it can be easily passed to the function and does not need to specify its size. An important feature that makes slices more powerful is slice expressions. A slice expression is a method of selecting subsequences from a slice, and its syntax is as follows:
Slice name [start index: end index]
This returns a new slice containing the elements from the start index to the end index. For example, to select an element with index 1 to index 3 from the "numbers" slice, you can use the following code:
var subSlice = numbers[1:4]
Note that the start index in the slice expression is included in the result, but the end index is not included in the result. In the example above, the result will contain the second, third and fourth elements in the "numbers" slice.
The slice expression also has optional parameters that specify the maximum capacity of the slice. If the slice expression is:
Slice name [Start index: End index: Maximum capacity]
Then the capacity of the resulting slice will be the maximum capacity-start index. This allows to create a "truncated" slice that does not contain any elements between the start index and the end index, but can accommodate other elements.
2.7 Slice sorting
The sort package in Golang provides a variety of sorting algorithms that can be used to sort slices. Here is an example of sorting slices:
slice := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} (slice) (slice) // Output [1 1 2 3 3 4 5 5 5 6 9]
The above code uses the Ints function to sort integer slices and outputs the sorted result.
3. String
A string is an immutable sequence of bytes. In Golang, a string is a sequence of characters enclosed in double quotes. For example, the following is a declaration of a string variable:
var str string = "hello world"
Unlike arrays and slices, strings are not a built-in type. In fact, a string is a slice represented by an array of bytes. Since strings are immutable, they must be manipulated with slices.
3.1 Accessing characters in strings
To access characters in a string, you can use the index operator. For example, the following code will output the first character of the string "hello world":
(str[0])
Each character in a string is represented by one byte. Therefore, accessing characters in the string will return the ASCII code value of that byte.
3.2 String Slicing
We can use slice expressions to create new string slices. For example, the following code creates a new string slice containing the first 5 characters of the string "hello world":
var subStr = str[:5]
Note that, like slices, the start index is included in the result, but the end index is not included in the result.
3.3 String operation
Golang provides some built-in string functions to make string operation more convenient. Here are some of the commonly used functions:
- len(): Returns the length of the string
- (): Check whether the string contains the specified substring
- (): Replace the specified substring in the string with another string
- (): Split the string into slices of substring
- () and (): Convert characters in a string to uppercase or lowercase
For example, the following code uses the "" function to check whether the string "hello world" contains the substring "world":
var contains = (str, "world") (contains) // Output true
3.4 Frequently Asked Questions about Strings
In Golang, you may encounter some common problems when processing strings. Here are some common problems and solutions:
3.4.1 How to convert a string to an integer?
In Golang, you can use the Atoi function in the strconv package to convert a string to an integer. For example, the following code converts the string "123" to an integer 123:
import "strconv" str := "123" num, err := (str) if err != nil { ("Conversion Error") } else { (num) }
If the string cannot be converted to an integer, the Atoi function returns an error.
3.4.2 How to convert integers to strings?
Integers can be converted to strings using the Itoa function in the strconv package. For example, the following code converts the integer 123 to the string "123":
import "strconv" num := 123 str := (num) (str)
3.4.3 How to check if a string is empty?
You can use the len function to check whether the string is empty. For example, the following code checks whether the string is empty:
str := "" if len(str) == 0 { ("String is empty") }
3.4.4 How to check if a string contains another string?
You can use the Contains function in the strings package to check whether a string contains another string. For example, the following code checks whether the string "hello world" contains the string "world":
import "strings" str := "hello world" if (str, "world") { ("Contains string world") }
3.4.5 How to compare two strings?
You can use the "==" operator to compare whether two strings are equal. For example, the following code compares the string "hello" with the string "hello":
str1 := "hello" str2 := "hello" if str1 == str2 { ("Strings equal") }
3.4.6 How to split a string into a substring?
You can use the Split function in the strings package to split a string into a substring. For example, the following code splits the string "hello,world" into "hello" and "world":
import "strings" str := "hello,world" arr := (str, ",") (arr)
3.4.7 How to convert a string to a byte array?
The string can be cast to type []byte, which will return a byte array containing the string. For example, the following code converts the string "hello" to a byte array:
str := "hello" bytes := []byte(str) (bytes)
3.4.8 How to convert a byte array to a string?
You can use the string function to convert a byte array into a string. For example, the following code converts the byte array []byte{104, 101, 108, 108, 111} to the string "hello":
bytes := []byte{104, 101, 108, 108, 111} str := string(bytes) (str)
4. Summary
Arrays, strings, and slices are important data structures in Golang. An array is a collection of fixed-size data elements that can directly access and modify elements in an array. A string is an immutable sequence of bytes that can be accessed through subscripts. A slice is a dynamic array that can be dynamically increased or reduced in size as needed. Slicing provides convenient operational functions and syntax, such as adding elements to slices, getting the length and capacity of slices, sorting slices, etc.
In Golang, arrays, strings, and slices are widely used, so it is important to understand and master their basic operations and syntax. At the same time, it is also necessary to understand their characteristics and advantages in Golang. For example, slicing can avoid the problem of insufficient or too long array length, and strings can be directly encoded using Unicode.
The above is the detailed content of in-depth analysis of arrays, strings and slices in Golang. For more information about Golang arrays, strings and slices, please pay attention to my other related articles!