Home >Backend Development >Golang >Composite data type analysis in Go language
Go language composite data types include: array: fixed-size element collection, index access. Slice: Dynamically sized data structure that can grow/shrink. Mapping: An unordered collection of key-value pairs. Structure: A composite type that organizes related data.
Detailed explanation of composite data types in Go language
Go language provides a variety of composite data types for storage and Organize complex data structures. These data types include arrays, slices, maps, and structures.
Array
An array is a fixed-size collection of elements, each element has a fixed index. The syntax of an array is as follows:
var array_name [size]type
For example, an array containing 5 integers can be declared as:
var numbers [5]int
Slice
A slice is similar to an array dynamically sized data structure. The syntax for slicing is as follows:
var slice_name []type
Unlike arrays, the size of a slice can dynamically grow or shrink as needed.
var numbers = []int{1, 2, 3, 4, 5}
Mapping
Mapping is an unordered collection of key-value pairs. The syntax of mapping is as follows:
var map_name map[key_type]value_type
For example, a mapping that maps strings to integers can be declared as:
var ages = make(map[string]int) ages["Alice"] = 25 ages["Bob"] = 30
Structure
Structure Is a composite type that organizes related data together. The syntax of the structure is as follows:
type struct_name struct { field_name1 type1 field_name2 type2 ... }
For example, a structure representing a character can be declared as:
type Person struct { name string age int }
Actual case
In the following code In the example, we use arrays, slices, maps, and structures to store and manipulate employee data.
package main import "fmt" type Employee struct { name string salary float64 } func main() { // 数组 employees := [5]Employee{ {"Alice", 1000}, {"Bob", 1200}, {"Carol", 1400}, {"Dave", 1600}, {"Eve", 1800}, } // 遍历数组 for _, employee := range employees { fmt.Printf("%s earns $%.2f\n", employee.name, employee.salary) } // 切片 ages := []int{25, 30, 35, 40, 45} // 遍历切片 for _, age := range ages { fmt.Println(age) } // 映射 agesMap := make(map[string]int) agesMap["Alice"] = 25 agesMap["Bob"] = 30 agesMap["Carol"] = 35 // 访问映射值 fmt.Println(agesMap["Alice"]) // 结构体 employee := Employee{ name: "John", salary: 2000, } // 访问结构体字段 fmt.Println(employee.name, employee.salary) }
The above is the detailed content of Composite data type analysis in Go language. For more information, please follow other related articles on the PHP Chinese website!