In Go language, data structures are a very important part of programming. They are used to store, organize and manipulate data. In this article, we will take an in-depth look at commonly used data structures in the Go language, including arrays, slices, maps, structures, and pointers, with specific code examples.
An array is a set of elements with the same data type and has a fixed length. In the Go language, the declaration method of an array is var variable name [length] element type
. Here is an example:
package main import "fmt" func main() { var numbers [3]int numbers[0] = 1 numbers[1] = 2 numbers[2] = 3 fmt.Println(numbers) // 输出 [1 2 3] }
A slice is a dynamic array with variable length. In the Go language, slices are declared as var variable name [] type
. Here is an example:
package main import "fmt" func main() { var numbers []int numbers = append(numbers, 1) numbers = append(numbers, 2) numbers = append(numbers, 3) fmt.Println(numbers) // 输出 [1 2 3] }
A mapping is a collection of key-value pairs, also called a dictionary. In the Go language, mapping is declared as var variable name map[key type] value type
. The following is an example:
package main import "fmt" func main() { students := make(map[string]int) students["Alice"] = 21 students["Bob"] = 22 fmt.Println(students["Alice"]) // 输出 21 }
The structure is a custom data type used to encapsulate multiple fields of different types. In the Go language, the structure is declared as type structure name struct {field 1 type 1; field 2 type 2 }
. Here is an example:
package main import "fmt" type Person struct { Name string Age int } func main() { var p Person p.Name = "Alice" p.Age = 21 fmt.Println(p) // 输出 {Alice 21} }
Pointer is a variable that stores the memory address of a variable. In the Go language, pointers are declared as var pointer name *type
. The following is an example:
package main import "fmt" func main() { x := 10 var ptr *int ptr = &x fmt.Println(*ptr) // 输出 10 }
The above are some commonly used data structures in the Go language and their corresponding code examples. Mastering the characteristics and usage of these data structures can help us program more efficiently and better understand how data is stored and manipulated. I hope this article can provide you with some help and inspiration.
The above is the detailed content of In-depth discussion: What are the data structures in Go language?. For more information, please follow other related articles on the PHP Chinese website!