Getting Started with Go Language: Composite Data Types

Previously, we had a preliminary exploration of the Go language world and learned about the basic data types. In order to meet different special needs, we have to use different ways to combine basic types to construct new composite data types - arrays, structures, slices. , map.

1. Array

An array is a fixed-length sequence of one or more elements of the same type.

For example:

One-dimensional array:

//声明一个数组
var arr[4]int
//声明并初始化数组
var brr = [3]int{1,2,3}

Two-dimensional array:

//声明一个二维数组
var a[3][3]int
//声明并初始化二维数组
var b = [5][5]int{
   
   {1,2,3,4,5}}

The built-in len function can return the number of elements in an array:

var a = [3]int{1,2}
fmt.Println(len(a)-1) //输出a[2]的值0

Each element of the array can be accessed through an index subscript, which ranges from 0 to the length of the array minus 1.

2. Slice

Because the length of the array is fixed, arrays are rarely used directly in the Go language. The corresponding type of array is Slice, which is a variable-length sequence with no fixed length. It can grow and shrink dynamic sequences and has a wider range of uses. .

2.1 Slice consists of three parts:
  • pointer
  • The number of elements in the length slice
  • The capacity is from the beginning of the slice to the end of the underlying data, that is, the amount of available space.
2.2 Define slices

A slice is a variable-length sequence, so you can declare an array of unspecified size to define a slice.

var 数组名字 []type

 Or use make definition:

var slice1 []type = make([]type, len)

//也可以简写为
slice1 := make([]type, len)

In addition to length, slices also have the concept of capacity. You can specify both length and capacity when declaring the slice.

s := make([]string,3,10)

A new slice s1 can be created through s1 := arr[startIndex:endIndex], and arr can be an array. The rest of the operations seem to be similar to python's slices, but go's slices are more like a variable-length array or linked list.

Go supports the append() function for appending values ​​to slices and the copy() function for copying slices.

Slices are indexable and the length can be obtained by the len() method.

Slices provide a method for calculating capacity, cap(), which can measure how long a slice can be.

3. Map

Hash table is an ingenious and practical data structure. It is an unordered collection of key-value pairs, where all keys are different, and then the corresponding value can be retrieved, updated or deleted within constant time complexity through a given key.

When getting the value of the Map, if the key does not exist, a zero value of the type is returned. For example, the zero value of the int type is 0, and the zero value of the string type is " ".

Map is a reference type. If a Map is passed to a function or assigned to another variable, they all point to the same underlying data structure, so modifications to the Map will affect all variables that reference it.

DefineMap

Maps can be defined using the built-in function make or using the map keyword:

/* 使用 make 函数 */
map_variable := make(map[KeyType]ValueType, initialCapacity)

Among them, KeyType is the type of key, ValueType is the type of value, and initialCapacity is an optional parameter used to specify the initial capacity of Map. The capacity of Map refers to the number of key-value pairs that can be saved in the Map. When the number of key-value pairs in the Map reaches the capacity, the Map will automatically expand. If initialCapacity is not specified, the Go language will choose an appropriate value based on the actual situation.

// 创建一个初始容量为 10 的 Map
m := make(map[string]int, 10)

// 使用字面量创建 Map
m := map[string]int{
    "student": 1,
    "teacher": 2,
    "school": 3,
}

Get elements:
// 获取键值对
v1 := m["student"]
v2, result := m["pen"]  // 如果键不存在,result 的值为 false,v2 的值为该类型的零值
Modify elements:
// 修改键值对
m["student"] = 5
Traverse the Map:
// 遍历 Map
for k, v := range m {
    fmt.Printf("key=%s, value=%d\n", k, v)
}
Delete elements:
// 删除键值对
delete(m, "teacher")

4. Structure

Arrays in Go language can store the same type of data, but in structures we can define different data types for different items.

A structure is a collection of data consisting of a series of data of the same type or different types. Use the classic case of structure to process the company's employee information. Each employee information contains a unique employee number, employee's name, home address, date of birth, job position, salary, superiors, etc. All this information needs to be bound to an entity, which can be copied as a whole unit, used as a parameter or return value of a function, or stored in an array, etc.

Structure definition requires the use of type and struct statements. The struct statement defines a new data type, with one or more members in the structure. The type statement sets the name of the structure. The structure declaration syntax is as follows:

type StructName struct{  
    FieldName type  
}

Once a structure type is defined, it can be used for variable declarations with the following syntax:

variable_name := structure_variable_type {value1, value2...valuen}
或
variable_name := structure_variable_type { key1: value1, key2: value2..., keyn: valuen}

Guess you like

Origin blog.csdn.net/weixin_53472334/article/details/132392773