Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. ### 切片
  2. ```go
  3. slice := []int{1,2,3,4,5}
  4. newSlice := slice[i:j:k]
  5. ```
  6. - newSlice长度:j-i
  7. - newSlice容量:k-i
  8.  
  9. ```go
  10. slice := []int{1,2,3,4,5}
  11. newSlice := slice[2:3]
  12. newSlice[0] = 10
  13. newSlice = append(newSlice, 0)
  14. fmt.Println(newSlice, slice)
  15. // Output:
  16. [10 0] [1 2 10 0 5]
  17. ```
  18. - 基于数组或切片创建的新切片,当新切片的容量未超过底层数组的容量时,对新切片中的元素改变,会同时改变底层数组元素,也就是说会影响引用底层数组的其他切片
  19.  
  20. ```go
  21. slice := []int{1,2,3,4,5}
  22. newSlice := slice[2:3]
  23. newSlice = append(newSlice, []int{0,0,0,0}...)
  24. fmt.Println(newSlice, slice)
  25. // Output:
  26. [3 0 0 0 0] [1 2 3 4 5]
  27. ```
  28. - 基于数组或切片创建的新切片,当新切片的容量超过底层数组的容量时,对新切片中的元素改变,不会改变底层数组元素,也不会影响引用底层数组的其他切片,因为新切片会创建一个新的数组
  29. - append算法:append函数会智能的增长底层数组的容量,当容量小于1000时,会成倍的增长,当超过1000时,增长因子为1.25,也就是说每次会增加25%的容量
  30.  
  31. ```go
  32. slice := []int{1, 2, 3, 4, 5}
  33. for _, v := range slice {
  34. v = 0
  35. fmt.Println(v)
  36. // Output: 0
  37. }
  38. fmt.Println(slice)
  39. // Output:
  40. [1 2 3 4 5]
  41. ```
  42. - for range循环中的值,只是原来切片中元素的拷贝,而不是元素的引用,所以对值的修改不能改变原来切片中的元素值
  43. - 可以使用`slice[k] = x`去改变原始切片中元素的值
  44.  
  45. ```go
  46. slice := []int{1, 2, 3, 4, 5}
  47. for i := 0; i < len(slice); i++ {
  48. slice[i] = 0
  49. }
  50. fmt.Println(slice)
  51. // Output:
  52. [0 0 0 0 0]
  53. ```
  54. - 可以在循环中改变切片中的值
  55.  
  56. ```go
  57. func main() {
  58. slice := []int{1, 2, 3, 4, 5}
  59. fmt.Printf("%p\n", &slice)
  60. modify(slice)
  61. fmt.Println(slice)
  62. }
  63.  
  64. func modify(slice []int) {
  65. fmt.Printf("%p\n", &slice)
  66. slice[1] = 10
  67. }
  68. // Output:
  69. 0xc00000c060
  70. 0xc00000c080
  71. [1 10 3 4 5]
  72. ```
  73. - 我们知道切片是3个字段构成的结构类型,所以在函数间以值的方式传递的时候,占用的内存非常小,成本很低。在传递复制切片的时候,其底层数组不会被复制,也不会受影响,复制只是复制的切片本身,不涉及底层数组
  74. - 函数间传递切片使用值传递,当我们修改一个索引的值后,发现原切片的值也被修改了,说明它们共用一个底层数组,在函数间传递切片非常高效,而且不需要传递指针和处理复杂的语法
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement