For ordinary language users, 20% of language characteristics can meet 80% of the usage needs, and the rest can be mastered during use. Based on this theory, the articles in the basic Go series will not deliberately pursue everything, but they will cover all knowledge points, with the purpose of taking you to catch up with Golang's new car.
Hurry up , Let's go !
We have learned the basic data types in Golang, such as built-in typesint
string
bool
So, there are actually some more complex but very useful compound types, similar to arrays andstruct
, in C++map
, Today we will learn about the compound types in Go.
Through this article, you will master the following knowledge:
- Structure
- Pointer type
- Arrays and slices
- Mapping type
pointer
The pointer does not save the content of the actual data, but saves the memory address pointing to the value. Use & to get the memory address of the variable and use * to access the pointed memory. This is the same as the pointer in C. The only difference is that the pointer in Go cannot be computed.
a := 3 pa := &a // Use `&` to fetch the memory address of the variable ("point", a, *pa) // use `*` To access the memory pointed to
Only declare that the pointer value that has not been assigned is nil, representing a null pointer.
var a0 *int // Only declare that the pointer without assignment is nil if a0 == nil { ("point", "it is nil point") }
Structure
Similar to the structure in C, a structure is an aggregated data type, an entity aggregated from zero or more values of any type. Each value is called a member of the structure, see the example:
type Test struct { a int b int }
Have you seen the grammatical difference? There is no semicolon after each structure field, and it is still very comfortable to write without semicolons.
initialization
Can be initialized at definition time
test := Test{1, 2} // Define structure variables and initialize them
Initialize some structure fields
t2 = Test{a: 3} //Specify the assignment as3 Implicit assignment0
Implicit initialization
t3 = Test{} // .a .bAll implicitly assigned0
Multiple variables can be assigned together
var ( t1 = Test{8, 6} t2 = Test{a: 3} //Specify assignment implicit assignment 0 t3 = Test{} // .a .b all implicitly assign 0 pt4 = &Test{8, 6} // Pointer)
Visit members
Access structure members through . operation, and do not distinguish between structure types or structure pointer types.
("struct", , ) // pass . Operation to access structure members
For structures that only declare no assignment, their internal variables are assigned zero values. Below we declare st0 but no assignment is given to it.
var st0 Test ("struct", , ) //Output:struct 0 0
Array
An array is a sequence of elements of a fixed length of specific types, and an array can be composed of zero or more elements. An array can access elements with subscripts, which start with 0.
Assign value after array declaration
var strarr [2]string // Array declaration syntax strarr[0] = "ready" strarr[1] = "go"
Declaration assignment is completed simultaneously
intarr := [5]int{6, 8, 9, 10, 7} // Declaration assignment is completed simultaneously
For arrays that determine the number of initial values, the array length can be omitted
intarr := [...]int{6, 8, 9, 10, 7} // Declaration assignment is completed simultaneously
Slice
Slices are variable-length sequences, and each element in the sequence has the same type. The slice syntax is very similar to an array, but it does not have a fixed length. The bottom layer of the slice refers to an array object, and modifying the slice will modify the original array.
Some or all elements of an array can be accessed through slices. Because the slice length is not fixed, slices are more commonly used than arrays.
Declaration and Initialization
Regular initialization
Short statement and initialize slices
s0 := []int{1, 2, 3, 4, 5, 6} // Short statement plus assignment
Initialize after declaration
var s []int // Declare slicess = s0 // Use slicess0Initialize slicess
Declare and initialize slices
var s00 []int = s0 // Use slicess0Initialize slicess
The zero value of the slice is nil
// The zero value of the slice is nil The length and capacity of the empty slice are 0var nilslice []int if nilslice == nil { ("slice", "nilslice is nil ", len(nilslice), cap(nilslice)) }
Make initialization
In addition to the above conventional initialization method, you can also use make built-in function to create slices.
// Built-in function make creates slices, specifying the slice length and capacity// Make function assigns an array of zero elements and returns a slice that references its2 := make([]int, 4, 6) //Create the slice s2 with all elements 0, length is 4, capacity is 6, and the third parameter can be omitted("slice", len(s2), cap(s2), s2)
Slice length
The length represents the number of elements in the slice, which can be obtained by the built-in function len function.
Slice capacity
Capacity represents the number of elements contained in the first element in the slice to the end of the referenced underlying array, which can be obtained by the built-in function cap.
Slice interval
The slice interval follows the principle of "close left and open right".
s0 := [5]int{6, 8, 9, 10, 7} // Array definitionvar slice []int = intarr[1:4] // Create slicesslice Contains array subsequences
The default upper and lower bounds. The default value of the lower bound of the slice is 0, and the default value of the upper bound is the length of the slice.
("slice", s0[:], s0[0:], s0[:5], s0[0:5]) // These four slices are the same
Slice append operation
The append function is used to append new elements at the end of the slice.
There are also two situations for adding elements.
After addition, the length is still within the original slice capacity range
s2 := make([]int, 4, 6) //Create the slice s2 with all elements 0, length is 4, capacity is 6, and the third parameter can be omitteds22 := append(s2, 2) // append is added at the end every time, so at this time, s21 s22 points to the same underlying array(s21, s22) // [0 0 0 0 2] [0 0 0 0 2]
The length exceeds the original slice capacity after adding elements
The new array space is allocated and a slice pointing to the newly allocated array is returned.
In the following example, the s24 slice has pointed to the newly allocated array, s22 still points to the original array space, and s24 has pointed to the new underlying array.
s24 := append(s2, 1, 2, 3) (s24, s22) // s24 [0 0 0 0 1 2 3] [0 0 0 0 2]
Two-dimensional slice
You can define slices of slices, similar to the usage of two-dimensional arrays in other languages. Reference code:
s3 := [][]int{ {1, 1, 1}, {2, 2, 2}, } (s3, s3[0], len(s3), cap(s3)) // Output: [[1 1 1] [2 2 2]] [1 1 1] 2 2
map map type
In Gomap
is a key-value pair type, representingkey
andvalue
A map is a reference to a hash table.
Definition and initialization
Define and initialize a map variable as follows
m0 := map[int]string{ 0: "0", 1: "1", }
You can also use the built-in make function to initialize a map variable and then add key-value pairs to it. Like this:
m1 := make(map[int]string) // Make function returns a map of the given type and initializes it as a standby if m1 != nil { ("map", "m1 is not nil", m1) // m1 is not nil } m1[0] = "1" m1[1] = "2"
Note: The map variable that only declares that it does not initialize is a nil map and cannot be used directly!
var m map[int]string // The uninitialized m-zero value is nil map if m == nil { ("map", "m is nil", m) } //m[0] = "1" // This sentence triggerspanicabnormal, The zero value of the map is nil 。nilThe map has neither keys,You can't add keys。
Element reading
Use syntax: vaule= m[key] Get the element corresponding to the key key vaule .
We only used one variable to get the element above. In fact, this operation will return two values. The first return value represents the element of the book, and the second return value represents the bool type that represents whether the key exists. For example:
v, st := m1[0] // v is the element value, and the element corresponding to the subscript exists st=true otherwise st=false _, st1 := m1[0] // _ Symbol means ignore the first element v1, _ := m1[0] // _ Symbol means ignore the second element (v, st, v1, st1, m1[2]) // m1[2]Does not exist,Return elementstringThe value of zero「Empty characters」
Delete elements
The built-in function delete can delete the map element, for example:
delete(m1, 1) // The delete key is 1 Elements
range traversal
range is used to traverse slices or maps.
Array or slice traversal
When you use a for loop and range to iterate through an array or slice, two values are returned for each iteration. The first value is the subscript of the current element, and the second value is a copy of the element corresponding to the subscript.
s1 := []int{1, 2, 3, 4, 5, 6} for key, vaule := range s1 { ("range", key, vaule) } for key := range s1 { // Just index and ignore the second variable ("range", key) } for _, vaule := range s1 { // Only element values are needed, and the index is ignored with '_' ("range", vaule) }
map traversal
When traversing maps with for loops and range, two values are returned for each iteration. The first value is the current element key and the second value is value.
m0 := map[int]string{ 0: "0", 1: "1", } ("map", m0) for k, v := range m0 { // range traversal map, return key and value ("map", "m0 key:", k, "vaule:", v) }
Summarize
Through the study of this article, we have mastered the basic control flow statements in Golang. Using these control statements plus the basic knowledge such as variables introduced in a section can form a rich program logic, and you can use Golang to do some interesting things.
Thank you for your reading. The purpose of the article is to share your understanding of knowledge. I will repeatedly verify technical articles to ensure the maximum accuracy. If there are obvious omissions in the article, please point them out, so let us learn together in discussion.
That’s all for today’s technology sharing, see you next time.
The above is the detailed content of the GO language compound type topic. For more information about GO compound type, please pay attention to my other related articles!