Go core development study notes (58) - Slice Slice

Ideas introduced: NBA players in each team needs to be saved with an array, but each team due to the trading problems, the number of players not sure, how to solve - Use slices.

  1. Slice can be understood as a dynamic array, similar to the python list .append (), a slice may vary in length, length of the array is not changed.
  2. Slice is a reference to an array type, passed by reference compliance mechanism during transfer.
  3. Traversal, access, len (slice) and the array are the same.
  4. Dynamic changes, dynamically increased with the increase of the element.
  5. The basic syntax: and array [n] different xx, defined slices [] is not a value of: var slice1 [] int, var slice2 [] float64 ...

Slice the basic use case:

package main
import "fmt"
func main() {
	 var intArray [5]int = [...]int{20,40,29,46,1}

	 //与python下标计算一样,取出来的值是(冒号后-冒号前),从下标为1的开始取,取三个
	 slice1 := intArray[3:4]
	 fmt.Println(slice1)               //打印出slice切片的取值
	 fmt.Println(cap(slice1))          //查看切片容量,动态智能增加,不会说增加一个元素,cap + 1,分批次
}

Slice distribution in memory:

  1. Slice is a reference type, and is a structure struct.

  2. In memory slice includes three parts:
    memory address (1) the starting position of the slice element, e.g. slice1: = intArray [3: 4 ] so that the intArray: & intArray [3].
    (2) slicing length, e.g. slice1: = intArray [3: 4 ] is length: 4 - 3 = 1.
    (3) slicing capacity, as previously mentioned, dynamic intelligence increased.

  3. On Article 2, var intArray [5] int = [...] int {20,40,29,46,1}, slice1: = intArray [1: 4]

    slice1 in memory distributed as follows: & intArray [. 1] -> (PTR) |. 3 -> (len) |. 4 -> (CAP)
    into the structure written:
    * type slice1 struct {
    PTR [. 3] int
    len int
    CAP int
    }

  4. Because it is a reference type, so the value in the slice changes will affect the value of the source array.

package main
import "fmt"
func main() {
	 var intArray [5]int = [...]int{20,40,29,46,1}

	 slice1 := intArray[0:4]
	 slice1[0] = 200
	 fmt.Println(intArray)      //这里发现intArray第一个值已经变为200
}

Slice in three ways using:

  1. Using the created array as slice object: var intArray [. 5] int = [...] {int} 20,40,29,46,1; slice1: intArray = [0:. 4]
    Tips:
    access microtome array elements value can slice through the array and maintenance, an array of programmer visible.

  2. () To create a slice, allocate a memory space with the new () use the same make, make () is used for reference types.
    var slice2 [] int = make ( [] int ,,) // slice length determines the number of elements, cap> = len, all elements 0

    Tips:
    After using make () to create a slice, make will create an array, the array has no name, the programmer is not visible, in-memory data access slice, slice can only be accessed as entry of foreign elements in the data it is not visible.

  3. Directly define sections: var slice2 [] = int [] int {2,3,4} , slice2 var [] = String [] {String "Durant", "James", "Kobe"}

Slice Note:
4 is not out of range, 0 ~ len (slicex).
5. slice: = intArray [n1: ] // n1 start until the last
slice: = intArray [: n2] // n2 to 0 for all values
slice: = intArray [:] // array of all values

  1. After defining a slice can not be used, because it is empty, take either the value from the array or added subsequently.

  2. Slices can be iterated, slice slice, slice2: = slice1 [:], even iteration, slice2 change an element in value, slice1 and intArray will change, because the point values ​​for the same memory space!

  3. Dynamically add sections using append () function is added to the end of the slice, append () after addition of a variable element is required receiving sections

    package main
    import "fmt"
    func main() {
    	/*
    	append()原理分析:底层新建一个数组,将新传递的值和slice的原值一并增加到一个新的数组里,让slice接收则指针指向新数组的首地址,
    	与此同时,slice原来指向的匿名数组就被当成垃圾回收了;让新的变量接收就不存在上述问题了,直接新的变量指向append后的数组。
    	 */
    	var slice []int = []int{100,200,300}
    	slice1 := append(slice,200,300,400)      
    	fmt.Println(slice1)                    //[100 200 300 200 300 400] append()本身并不改变源切片的值
    	fmt.Println(slice)                     //[100 200 300]  
    	slice = append(slice,slice...)         // 自己追加自己,再把新的切片赋值给自己,也可以;slice...是固定写法
    } 
    
  4. Slice copy (slice-dest, slice-src) built-in function, the completion of copying slices, slice are two types of parameters, not other types

    package main
    import "fmt"
    func main() {
    	var slice1 []int = []int{1,2,3,4,5}
    	var slice2 []int = []int{6,7,8,9,0,11,12,13}    
    	copy(slice1,slice2)                  //后面的参数会覆盖前面参数的slice对应位置的值
    	fmt.Println(slice1)
    	fmt.Println(slice2)
    }
    

    Notes:
    (1) two slices of data types must be the same!
    (2) If the length of the source exceeds the target slice length slice, the target slice of eventual slice value corresponding to the source, a source outside the slice section will be lost.
    (3) If the length of the source is less than the slice length of the target slice, the target slice sections based on the source location, change their value, the remaining uncovered part of the same.

  5. A note string and slice of:
    (. 1) is a string underlying byte array, it is possible to slice, the form in memory is the string: "ABCD" ----> A | B | C | D
    (2) string itself is not changed, a value can not be changed by the slice string way, for example, the "abcd" into "accd", the slice can not
    (3) If you want to change a value in the string may be first converted into string sections [] or byte [] Rune, modified, and then turning into a string

    package main
    import "fmt"
    func main() {
    	/*
    	思路:string在Golang底层是一个byte数组
    	 */
    	str := "Kurant"                   
    	arr := []byte(str)                   //把str转换成一个byte数组,只能处理英文和数字,不能处理中文
    	arr[0] = 'D'                         //把首字母改成D,记得byte的值要用单引号'',不要用""
    	str = string(arr)                    //修改后把array转换成字符string
    	fmt.Println(str)             
    	
    	str_chs := "库兰特"                   //[]rune是按照字符处理数组的,可以处理3字节的中文
    	arr1 := []rune(str_chs)
    	arr1[0] = '杜'                    
    	str_chs = string(arr1)
    	fmt.Println(str_chs)
    }
    
  6. Case, complete with a slice Fibonacci number sequence assignment deed

    package main
    import "fmt"
    func main() {
    	var n int
    	fmt.Println("请输入斐波那契数列的长度值: ")
    	fmt.Scanf("%d",&n)
    	var slice []uint64 = make([]uint64,n)          //定义一个切片接收变量,或者使用递归推导斐波那契函数
    	slice[0] = 1
    	slice[1] = 1
    	for i := 2 ; i < n ; i++ {
    		slice[i] = slice[i-1] + slice[i-2]
    	}
    	fmt.Println(slice)
    }
    
Published 49 original articles · won praise 18 · views 4011

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/89846668