Go language built-in containers (array, slice and map)

Go language built-in containers (array, slice and map)

The built-in containers of Go language mainly include array, slice and map.

 

Array

Array is a set of data item sequences with the same type and fixed length. This set of data item sequences are stored in a continuous area in memory. The size of the array cannot be changed after that.

 

Declaration array

The format is as follows:

var Array variable name [Array length]Element type
// Example:
var student [3]string
var grid [4][5]bool // Two dimensional array

 

Initialize array

  1. Arrays can be assigned when declared:

    var student [3]string{"Tom", "Ben", "Peter"}
    
  2. You can use... Instead of the number in brackets. The Go language compiler can set the size of the array according to the number of elements during compilation

    var student = [...]string{"Tom", "Ben", "Peter"}
    

 

Array is a value type

  1. [10]int and [20]int are different types
  2. When an array variable is assigned to another array variable, it is a replica and reopens a space
  3. You can use = = to compare whether the values in the array are equal

 

Slice

Slice also represents a continuous set of multiple elements of the same type, but the length of slice is variable. Because the length is variable, the problem of wasting memory when the number of data is uncertain can be solved.

However, the slice itself does not store any elements, but only a reference to an existing array. (that is, slice itself has no data and is a view of the underlying array)

	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s := arr[2:6]
	s[0] = 10
	fmt.Println(arr)// [0 1 10 3 4 5 6 7]

The slice structure includes address, length and capacity.

  1. Address: the address of the slice generally refers to the memory address pointed to by the first element in the slice, expressed in hexadecimal.
  2. Length: the actual number of elements in the slice.
  3. Capacity: the number from the starting element of the slice to the last element in its underlying array.

The length and capacity of the slice are not fixed. You can increase the length and capacity of the slice by adding elements.

There are three main ways to generate slices:

  1. Generate a new slice from the array
  2. Generate a new slice from the slice
  3. Generate a new slice directly

 

Generate a new slice from the array / slice

The format is as follows:

slice [Start position:End position]

Example:

	var student = [...]string{"Tom", "Ben", "Peter"}
	var student1 = student[1:3] // Generate a new slice from the array
	var student2 = student1[0:1] // Generate a new slice from the slice
	fmt.Println("student Array:", student)
	fmt.Println("student1 section:", student1)
	fmt.Println("student2 section:", student2)
	fmt.Println("student The array address is:", &student[1]) // Here we take the address of the student[1] element
	fmt.Println("student1 The slice address is:", &student1[0])
	fmt.Println("student2 The slice address is:", &student2[0])
	fmt.Println("student1 Slice length:", len(student1))
	fmt.Println("student1 Slice capacity:", cap(student1))
	fmt.Println("student2 Slice length:", len(student2))
	fmt.Println("student2 Slice capacity:", cap(student2))

The running result of the above code is:

According to the running results, we can conclude that generating new slices from arrays or slices has the following characteristics:

  1. Newly generated slice length: end position - start position
  2. The elements extracted from the newly generated slice do not include the elements corresponding to the end position
  3. The newly generated slice is a reference to an existing array or slice, and its address is the same as the element address corresponding to the start position of the intercepted array or slice.
  4. The newly generated slice capacity refers to the number from the start element of the slice to the last element in its underlying array.

 

Generate a new slice directly

Declaration slice

var Slice variable name []Element type

 

Initialize slice

  1. Initialize while declaring

    var student = []string{"Tom", "Ben", "Peter"}
    
  2. Initialize with the make() function

    1. After declaring the slice, you can initialize the slice through the built-in function make(). The format is as follows:

      make ([]Element type, Slice length, Slice capacity)
      

      There should be a rough estimate of the capacity of the slice. If the capacity value is too small, multiple expansion of the slice will cause performance loss.

    2. Example:

      var student []int
      student = make([]int, 2, 10) // After the student slice is initialized, the 0 value is automatically filled in
      

 

slice extension

	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]

What is the value of s1? What is the value of s2?


  1. The value of s1 is [2 3 4 5], and the value of s2 is [5 6]
  2. slice can be extended backward, not forward
  3. [i] Where I cannot exceed len(s), and backward expansion cannot exceed the underlying array cap(s)

 

Adding elements to slices

In Go language, we can use the append() function to add elements to the slice.

	var student = [...]string{"Tom", "Ben", "Peter"}
	var student1 = student[0:1]
	fmt.Println("student Array:", student)
	fmt.Println("student1 section:", student1)
	student1 = append(student1, "Danny") // Adding to the element of student1 slice will overwrite the element corresponding to the reference array
	fmt.Println("expansion Danny Posterior student1 section:", student1,", Slice length:", len(student1),
		",Slice capacity:",cap(student1))
	fmt.Println("expansion Danny Posterior student Array:", student)

Adding elements to the student1 slice will overwrite the elements corresponding to the reference array. Therefore, if the slice is generated from other arrays or slices, the element addition of the new slice needs to consider the impact on the data in the original array.

When the slice can no longer accommodate other elements (that is, the current slice length value is equal to the capacity value), the next time you use the append() function to add elements to the slice, the system will reallocate a larger underlying array, and the capacity will be expanded by twice.

	arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
	s1 := arr[2:6]
	s2 := s1[3:5]
	s3 := append(s2, 10) // [5 6 10]
	s4 := append(s3, 11) // [5 6 10 11]
	s5 := append(s4, 12) // [5 6 10 11 12]
	// arr [0 1 2 3 4 5 6 10]

 

Delete element from slice

Because the Go language does not provide a method for deleting slice elements, we need to manually connect the elements before and after the deleted element point to delete the elements in the slice

	var student = []string{"Tom", "Ben", "Peter", "Danny"}
	student = append(student[0:1], student[2:]...) // Equivalent to the next line of comment code
	// student = append(student[0:1], student[2], student[3])
	fmt.Println("student section:", student)
	fmt.Println("student Slice length:", len(student))
	fmt.Println("student Slice capacity:", cap(student))

 

Map

A map is an unordered collection of key value pairs. The key of a map is similar to an index and points to the value of data.

 

Declaration mapping

The format is as follows:

var map [Key type]Value type

Get element: m[key].

  1. When the key does not exist, the initial value of value type is obtained
  2. Use value, OK: = m [key] to determine whether there is a key
  3. The key is unique. Adding a duplicate key will overwrite the previous element

 

Initialize mapping

  1. Initialize while declaring

    var studentScoreMap = map[string]int {
        "Tom" : 80,
        "Ben" : 85,
        "Peter" : 90,
    }
    
  2. Initialize with the make() function

    make(map[Key type]Value type, map capacity)
    

    When using the make() function to initialize a map, you can not specify the map capacity, but multiple expansion of the map will cause performance loss.

    The cap() function can only be used to obtain the capacity of slices, but cannot obtain the capacity of map.

 

Remove key value pairs from mapping

The Go language deletes the specified key value pairs in the map through the delete() function. The format is as follows:

delete(map example,key)
  1. If the key exists, delete the element
  2. If the key does not exist, the contents in the map will remain unchanged and no error will be reported

The Go language does not provide a method to empty all elements for a map. The only way to empty a map is to redefine a new map.

 

key type of map and traversal of map

  1. Type of key
    1. map stores a set of key value pairs as a hash table, so keys must be comparable.
    2. Except slice, map and function, all built-in types can be used as key s
    3. The struct type does not contain the above fields and can also be used as a key
  2. Traversal of map
    1. Use range to traverse key or key and value pairs
    2. The traversal order is random. If you need a specific order, you need to manually sort the key s
    3. You can use len to get the number of map elements, not cap to get the capacity

Tags: Go Back-end

Posted on Tue, 23 Nov 2021 04:22:13 -0500 by Tonic-_-