Guest User

Untitled

a guest
Jan 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.03 KB | None | 0 0
  1. // Slices
  2. // An array has a fixed size. A slice, on the other hand, is a dynamically-sized,
  3. // flexible view into the elements of an array. In practice, slices are much more
  4. // common than arrays.
  5. //
  6. // The type []T is a slice with elements of type T.
  7. //
  8. // A slice is formed by specifying two indices, a low and high bound, separated by a colon:
  9. // a[low : high]
  10. // This selects a half-open range which includes the first element, but excludes the last one.
  11. //
  12. // The following expression creates a slice which includes elements 1 through 3 of a:
  13. // a[1:4]
  14. package main
  15.  
  16. import (
  17. "fmt"
  18. "strings"
  19. )
  20.  
  21. func main() {
  22. slices()
  23. sliceLiterals()
  24. sliceDefaults()
  25. sliceLengthAndCapacity()
  26. nilSlices()
  27. creatingSliceWithMake()
  28. slicesOfSlices()
  29. appendingToSlice()
  30. fmt.Println("")
  31. }
  32.  
  33. func slices() {
  34. fmt.Println("\n**Slices**")
  35. primes := [6]int{2, 3, 5, 7, 11, 13}
  36. // this selects a half-open range which includes the first element (3),
  37. // but excludes the last one (11).
  38. var s []int = primes[1:4]
  39. fmt.Println(s)
  40. }
  41.  
  42. func sliceLiterals() {
  43. fmt.Println("\n**Slice Literals**")
  44. // A slice literal is like an array literal without the length.
  45. // This creates the same array as above, then builds a slice that references it:
  46. // []bool{true, true, false}
  47.  
  48. q := []int{2, 3, 5, 7, 11, 13}
  49. fmt.Println(q)
  50.  
  51. r := []bool { true, false, true, true, false, true }
  52. fmt.Println(r)
  53.  
  54. s := []struct {
  55. i int
  56. b bool
  57. } {
  58. {2, true},
  59. {3, false},
  60. {5, true},
  61. {7, true},
  62. {11, false},
  63. {13, true},
  64. }
  65. fmt.Println(s)
  66. }
  67.  
  68. func sliceDefaults() {
  69. fmt.Println("\n**Slices Defaults**")
  70. // When slicing, you may omit the high or low bounds to use their defaults instead.
  71. // The default is zero for the low bound and the length of the slice for the high bound.
  72. s := []int{2, 3, 5, 7, 11, 13}
  73.  
  74. s = s[1:4]
  75. fmt.Println(s) // [3 5 7]
  76.  
  77. s = s[:2]
  78. fmt.Println(s) // [3 5]
  79.  
  80. s = s[1:]
  81. fmt.Println(s) // [5]
  82. }
  83.  
  84. func sliceLengthAndCapacity() {
  85. fmt.Println("\n**Slice length and capacity**")
  86. // A slice has both a length and a capacity.
  87. //
  88. // The length of a slice is the number of elements it contains.
  89. //
  90. // The capacity of a slice is the number of elements in the underlying array,
  91. // counting from the first element in the slice.
  92. //
  93. // The length and capacity of a slice s can be obtained using the expressions
  94. // len(s) and cap(s).
  95. //
  96. // You can extend a slice's length by re-slicing it, provided it has sufficient
  97. // capacity.
  98.  
  99. s := []int{2, 3, 5, 7, 11, 13}
  100. printSlice(s)
  101.  
  102. // Slice the slice to give it zero length.
  103. s = s[:0]
  104. printSlice(s)
  105.  
  106. // Extend its length.
  107. s = s[:4]
  108. printSlice(s)
  109.  
  110. // Try to extent beyond its capacity
  111. // s = s[:7] // runtime error: slice bounds out of range
  112. // printSlice(s)
  113. }
  114.  
  115. func nilSlices() {
  116. fmt.Println("\n**Nil Slices**")
  117. // The zero value of a slice is nil.
  118. // A nil slice has a length and capacity of 0 and has no underlying array.
  119. var s []int
  120. fmt.Printf("slice=%v length=%v capacity=%v\n",s, len(s), cap(s))
  121. if s == nil {
  122. fmt.Println("nil!")
  123. }
  124. }
  125.  
  126. func creatingSliceWithMake() {
  127. fmt.Println("\n**Creating a slice with make**")
  128. // Slices can be created with the built-in make function
  129. // This is how you create dynamically-sized arrays.
  130.  
  131. // The "make" function allocates a zeroed array and returns a slice that refers to that array:
  132. a := make([]int, 5) // len(a)=5
  133. logSlice("a", a)
  134.  
  135. // To specify a capacity, pass a third argument to make:
  136. b := make([]int, 0, 5)
  137. logSlice("b", b)
  138.  
  139. c := b[:2]
  140. logSlice("c", c)
  141.  
  142. d := c[2:5]
  143. logSlice("d", d)
  144. }
  145.  
  146. func slicesOfSlices() {
  147. fmt.Println("\n**Slices of slices**")
  148. // Slices can contain any type, including other slices.
  149.  
  150. // Create a tic-tac-toe board.
  151. board := [][]string{
  152. []string{"_", "_", "_"},
  153. []string{"_", "_", "_"},
  154. []string{"_", "_", "_"},
  155. }
  156.  
  157. // The players take turns.
  158. board[0][0] = "X"
  159. board[2][2] = "O"
  160. board[1][2] = "X"
  161. board[1][0] = "O"
  162. board[0][2] = "X"
  163.  
  164. for i := 0; i < len(board); i++ {
  165. fmt.Printf("%s\n", strings.Join(board[i], " "))
  166. }
  167. }
  168.  
  169. func appendingToSlice() {
  170. fmt.Println("\n**Appending to a slice**")
  171. // It is common to append new elements to a slice, and so Go provides a built-in append function.
  172. // func append(s []T, vs ...T) []T
  173. // The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.
  174. //
  175. // The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
  176. //
  177. // If the backing array of s is too small to fit all the given values a bigger array will be allocated.
  178. // The returned slice will point to the newly allocated array.
  179. var s []int
  180. printSlice(s)
  181.  
  182. // append works on nil slices.
  183. s = append(s, 0)
  184. printSlice(s)
  185.  
  186. // The slice grows as needed.
  187. s = append(s, 1)
  188. printSlice(s)
  189.  
  190. // We can add more than one element at a time.
  191. s = append(s, 2, 3, 4)
  192. printSlice(s)
  193. }
  194.  
  195.  
  196.  
  197.  
  198. // Helpers
  199.  
  200. func printSlice(s []int) {
  201. fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
  202. }
  203.  
  204. func logSlice(s string, x []int) {
  205. fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x)
  206. }
Add Comment
Please, Sign In to add comment