“This is my 13th day of the August Gwen Challenge

slice

  • Slice is the English name of slice
  • Slice: a sequence of elements of the same type with variable length.
  • Since the length is variable, it can solve the problem of wasting memory when the number of data is uncertain.
  • The main syntax difference between slicing and array declarations is length
	var slice []string  / / section
	var array [3]string / / array
Copy the code
  • When slice is declared, it is nil, no memory space is opened, slice cannot be operated directly, it needs to be initialized first
    • Note: Slice can only be equal to nil
	var slice []string  / / section
	fmt.Println(slice==nil)/ / output: true
	fmt.Printf("%p",slice)/ / output: 0 x0
Copy the code

Definition section

  • Initializes a slice variable by specifying an initial value directly
	names := []string{"hello"."world"}
	fmt.Println(names)
Copy the code
  • Once you’ve defined the slice, you can passSlice object [footer]Extract or modify the element content in the slice. The syntax is the same as for arrays

Slice is a reference type

  • Reference types pass addresses when assigning values between variables. A reference type variable is a pointer to that type. A slice is a reference type
  • Value types pass copies of values when assigning values between variables
	names := []string{"hello"."world"}
	names1 := names
	names1[0] = "a"
	fmt.Println(names, names1)// Output :[a world] [a world]
	fmt.Printf("%p %p",names,names1)// Same address
Copy the code

Make function

  • The make function can be used to create slice, map, channel, and interface in Go
  • Use the make function to define a slice that has no content but is not nil, meaning that the slice has allocated memory
    • Make (type, initial length [, initial capacity])
    • The initial capacity can be omitted and is equal to the length by default
	slice := make([]string.0)     // Slice of length 0, no third argument indicating equal capacity and length
	slice1 := make([]string.0.2) // The length is 0 and the capacity is 2
	fmt.Println(slice, slice1)
Copy the code
  • The length represents the actual number of elements in the slice, and the capacity represents the space occupied by the slice, and the slice capacity increases exponentially. When it reaches 1024, it increases by a certain percentage.
    • Len (slice) Views the length of the slice
    • Cap (slice) Views the capacity of a slice
	slice := make([]string.0)     // Slice of length 0, no third argument indicating equal capacity and length
	slice1 := make([]string.0.3) // The length is 0 and the capacity is 2
	fmt.Println(len(slice), cap(slice))
	fmt.Println(len(slice1), cap(slice1))
Copy the code

Append () function

  • Append () is available in the Go library as follows
// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//	slice = append(slice, elem1, elem2)
//	slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
//	slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ... Type) []Type
Copy the code
  • You can add one or more values to a slice, and you must use the slice to receive the value returned by the append() function
	s := make([]string.0)
	fmt.Println(len(s), cap(s))// Output :0 0
	s = append(s, "msr"."MaiShuRen")
	fmt.Println(len(s), cap(s))// Output :2 2
	s = append(s, "MaiShuRen")
	fmt.Println(len(s), cap(s))// Output :3, 4
Copy the code
  • If multiple values are added at a time and the added length is larger than the capacity expansion, the capacity and length are the same. Wait until the next time to add content, if it does not exceed the size of the expansion, on the current basis to double
	s := make([]string.0)
	fmt.Println(len(s), cap(s)) // Output :0 0
	s = append(s, "msr"."MaiShuRen")
	fmt.Println(len(s), cap(s)) // Output :2 2
	s = append(s, "MaiShuRen")
	fmt.Println(len(s), cap(s)) // Output :3, 4
	s = append(s, "4"."5"."6"."Seven"."8"."9")
	fmt.Println(len(s), cap(s)) // Output :9, 9
	s = append(s,"10")
	fmt.Println(len(s), cap(s)) // Output :10, 18
Copy the code
  • You can also add the contents of one slice directly to another. Notice that there are three points in the syntax
	s := make([]string.0)
	s1 := []string{"msr"."MaiShuRen"}
	s = append(s, s1...) // Note that there must be three points
	fmt.Println(s)
Copy the code

Generates slices from arrays

  • After defining an array, extract a fragment of the array, which is the slice type
	names := [3]string{"msr"."MaiShuRen"."Mai"}
	s := names[0:2]     // Pack before pack, not after pack
	fmt.Printf("%T", s) / / output: [] string
	fmt.Println(s)      // Output :[MSR MaiShuRen]
Copy the code
  • A slice is a pointer to the address of an array element. If you modify the contents of the slice, the contents of the array will change
	names := [3]string{"msr"."MaiShuRen"."Mai"}
	s := names[0:2] // Pack before pack, not after pack
	fmt.Printf("%p %p",s,&names[0])// The output address is the same
	s[0] = "The language"
	fmt.Println(s)     // Output :[Go MaiShuRen]
	fmt.Println(names) // Output :[Go MaiShuRen Mai]
Copy the code
  • When the slice content is increasing
    • If the length of the increment slice does not exceed the array, modifying the slice is also modifying the array
    • If the length of the slice exceeds the array, a new space is created for the contents of the slice
    • The following code also confirms that the contents of a slice have a contiguous space (like an array)
	names := [3]string{"msr"."MaiShuRen"."Mai"}
	s := names[0:2] // Pack before pack, not after pack
	fmt.Printf("%p %p\n",s,&names[0])
	s[0] = "The language"
	s=append(s,"Blockchain")
	fmt.Println(s)     // Output :[Go language MaiShuRen blockchain]
	fmt.Println(names) // Output :[Go language MaiShuRen blockchain]
	fmt.Printf("%p %p\n",s,&names[0])// Same address

	s=append(s,"Out of array length")
	fmt.Println(s)     // Output :[Go MaiShuRen blockchain exceeds array length]
	fmt.Println(names) // Output :[Go language MaiShuRen blockchain]
	fmt.Printf("%p %p\n",s,&names[0])// Slice address changed
Copy the code

Delete the implementation

  • The Go language standard library does not provide a delete function
  • Slice can also take a section of it to form a sub-slice, using this feature can achieve deletion effect
	num := []int {0.1.2.3.4.5.6}
	// To delete the element with the pin n
	n:= 2
	num1 :=num[0:n]
	num1= append(num1,num[n+1:]...). fmt.Println(num1)Copy the code

The copy function

  • The copy function copies the contents of one slice to another
  • The Go language standard library source code is defined as follows
    • The first parameter is the target slice, which receives the contents of the second parameter
    • The second argument is the source slice, which copies the content into the first argument
// The copy built-in function copies elements from a source slice into a
// destination slice. (As a special case, it also will copy bytes from a
// string to a slice of bytes.) The source and destination may overlap. Copy
// returns the number of elements copied, which will be the minimum of
// len(src) and len(dst).
func copy(dst, src []Type) int
Copy the code
  • Copy strictly according to the script. And the target slice will not be expanded

Code sample

  • Copy the short section into the long section
	s1:=[]int {1.2}
	s2:=[]int {3.4.5.6}
	copy(s2,s1)
	fmt.Println(s1)// Output :[1 2]
	fmt.Println(s2)// Output :[1 2 5 6]
Copy the code
  • Copy the long section into the short section
	s1:=[]int {1.2}
	s2:=[]int {3.4.5.6}
	copy(s1,s2)
	fmt.Println(s1)// Output :[3 4]
	fmt.Println(s2)// Output :[3 4 5 6]
Copy the code
  • Copy the slice fragment into the slice
	s1:=[]int {1.2}
	s2:=[]int {3.4.5.6}
	copy(s1,s2[1:])
	fmt.Println(s1)// Output :[4 5]
	fmt.Println(s2)// Output :[3 4 5 6]
Copy the code

Copy is used to delete elements

  • Use copy to keep the contents of the original slice unchanged
	s := []int{1.2.3.4.5.6.7}
	n := 2 // Drop the index of the element
	newSlice := make([]int, n)
	copy(newSlice, s[0:n])
	newSlice = append(newSlice, s[n+1:]...). fmt.Println(s)// The original slice remains unchanged
	fmt.Println(newSlice) // Delete the slice after the specified element
Copy the code

Slice capacity expansion policy

  1. If the requested capacity is more than twice the original capacity, expand the capacity to the new capacity. For example, if you add 6 elements into the section with length 3 and capacity 4, the length will become 9, which is twice larger than the original capacity, so the new capacity of the section will also become 9
  2. If less than 1024, double the capacity
  3. If the value is greater than 1024, the capacity is expanded according to 1.25
  4. Capacity expansion policies vary according to the type of storage values