2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
In our previous article, we introduced if and for. Let's practice how to use them.continue
Statement to calculate the sum of even numbers within 100. As we write the code,continue
The statement will help us skip certain unwanted iterations, for example, in this case, we will skip all the odd numbers.
- sum := 0
- for i := 1; i < 100; i++{
- if i & 1 == 0 {
- continue
- }
- sum += i
- }
-
- fmt.Println("the sum is",sum)
In programming, we often need to process a group of elements of the same type, and these element collections are represented by specific data structures in the Go language. Today, I will introduce several collection types in Go in detail: array, slice, and map.
First, let's start with arrays. An array is the most basic data structure in Go. It is a fixed-length sequence of elements of the same type. Once an array is declared, its length cannot be changed. The declaration and initialization of an array is very simple.
When declaring an array, you need to specify the array type and the array length. Here is how to declare an array:
var arrayName [arrayLength]elementType
For example, to declare an integer array of length 5:
var numbers [5]int
You can initialize arrays in a number of ways:
var numbers = [5]int{1, 2, 3, 4, 5}
:=
Short statement:numbers := [5]int{1, 2, 3, 4, 5}
numbers := [...]int{1, 2, 3, 4, 5}
numbers := [5]int{0: 1, 4: 5}
You can access elements in an array by their index, starting at 0:
value := numbers[2] // 获取索引为 2 的元素
you can usefor
Loop through all elements in an array:
- for i, value := range numbers {
- fmt.Printf("Index: %d, Value: %dn", i, value)
- }
You can use the built-inlen
Function to get the length of an array:
length := len(numbers)
If an array is not explicitly initialized, its elements are automatically set to the zero value for its type. For example, the zero value for an array of integer type is 0:
var numbers [5]int // 所有元素都是 0
Go also supports multidimensional arrays. The following is an example of declaring and initializing a 2x3 integer array:
- var matrix [2][3]int
- matrix = [2][3]int{{1, 2, 3}, {4, 5, 6}}
Since arrays are fixed length, this may not be very flexible in some cases. If you need a variable length collection, you can use slices.
Next is the slice, which is a more flexible built-in type that can be thought of as a dynamic array. The length of the slice is variable, and it is created based on the array, providing more convenience. Here is how to declare and initialize a slice:
- s := make([]int, 3) // 创建一个长度为3的整型切片
- s[0] = 1 // 切片元素赋值
- s[1] = 2
- s[2] = 3
- s = append(s, 4) // 向切片追加元素
In Go, although arrays and slices are both used to store a series of elements of the same type, they differ significantly in memory allocation, size variability, and usage. The following are the main differences between arrays and slices:
[3]int
and[4]int
Are different types.[]int
Is the common type for all integer slices.make
function or by slicing from an array, without specifying the size.The following are examples of array and slice initialization:
- // 数组
- var arr [3]int = [3]int{1, 2, 3}
-
- // 切片
- var slice []int = []int{1, 2, 3}
- // 或者使用 make 函数
- slice := make([]int, 3)
append
Functions add elements, or obtain subslices through slicing operations. The underlying array of the slice may be allocated on the heap, and the time complexity of accessing slice elements is also O(1), butappend
May cause reallocation of the underlying array, which is typically an O(n) operation.Finally, let's look at maps. Maps are associative arrays in Go that map keys to values. Map keys can be any type supported by the equality operator, such as integers, floating point numbers, strings, pointers, interfaces (as long as the values contained in the interface are comparable), structures, and arrays. Map values can be of any type.
The syntax for declaring a map is as follows:
var mapName map[keyType]valueType
For example, to declare a map with keys of string type and values of integer type:
var scores map[string]int
After declaring the map, you need to passmake
function to initialize it so that it can be used:
scores = make(map[string]int)
Alternatively, you can use a short declaration and initialization:
scores := make(map[string]int)
It is also possible to use literal initialization at the same time as declaration:
- scores := map[string]int{
- "alice": 90,
- "bob": 85,
- "charlie": 88,
- }
scores["alice"] = 90
value := scores["alice"]
If the key does not exist, the zero value for that value type is returned.
You can use the comma-ok idiom to check if a key exists in the map:
- value, exists := scores["alice"]
- if exists {
- // 键存在
- } else {
- // 键不存在
- }
usedelete
This function can be used to remove a key-value pair from a map:
delete(scores, "alice")
If the key does not exist,delete
The function does nothing.
usefor
The loop can iterate over all key-value pairs in the map:
- for key, value := range scores {
- fmt.Printf("%s: %dn", key, value)
- }
The zero value of the map isnil
.onenil
Maps have no underlying data structure and cannot have elements added to them. Before adding elements to a map, you must usemake
Initialize it.
You can use the built-inlen
Function to get the number of key-value pairs in the map:
length := len(scores)
The keys of a map can be of any comparable type, such as integers, floating-point numbers, strings, pointers, interfaces (as long as the values contained in the interface are comparable), structures, arrays, etc. Slices, maps, and functions cannot be used as map keys because these types do not support equality comparison.
In Go, arrays, slices, and maps are three commonly used data structures, each with different characteristics and considerations. Here are some points to note when using them:
nil
, needs to be initialized before use.nil
,nil
Map cannot be used to store key-value pairs and must be initialized before use.delete
Deleting a nonexistent key will not generate an error, but it is safe to check if the key exists.