Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Slices
- // An array has a fixed size. A slice, on the other hand, is a dynamically-sized,
- // flexible view into the elements of an array. In practice, slices are much more
- // common than arrays.
- //
- // The type []T is a slice with elements of type T.
- //
- // A slice is formed by specifying two indices, a low and high bound, separated by a colon:
- // a[low : high]
- // This selects a half-open range which includes the first element, but excludes the last one.
- //
- // The following expression creates a slice which includes elements 1 through 3 of a:
- // a[1:4]
- package main
- import (
- "fmt"
- "strings"
- )
- func main() {
- slices()
- sliceLiterals()
- sliceDefaults()
- sliceLengthAndCapacity()
- nilSlices()
- creatingSliceWithMake()
- slicesOfSlices()
- appendingToSlice()
- fmt.Println("")
- }
- func slices() {
- fmt.Println("\n**Slices**")
- primes := [6]int{2, 3, 5, 7, 11, 13}
- // this selects a half-open range which includes the first element (3),
- // but excludes the last one (11).
- var s []int = primes[1:4]
- fmt.Println(s)
- }
- func sliceLiterals() {
- fmt.Println("\n**Slice Literals**")
- // A slice literal is like an array literal without the length.
- // This creates the same array as above, then builds a slice that references it:
- // []bool{true, true, false}
- q := []int{2, 3, 5, 7, 11, 13}
- fmt.Println(q)
- r := []bool { true, false, true, true, false, true }
- fmt.Println(r)
- s := []struct {
- i int
- b bool
- } {
- {2, true},
- {3, false},
- {5, true},
- {7, true},
- {11, false},
- {13, true},
- }
- fmt.Println(s)
- }
- func sliceDefaults() {
- fmt.Println("\n**Slices Defaults**")
- // When slicing, you may omit the high or low bounds to use their defaults instead.
- // The default is zero for the low bound and the length of the slice for the high bound.
- s := []int{2, 3, 5, 7, 11, 13}
- s = s[1:4]
- fmt.Println(s) // [3 5 7]
- s = s[:2]
- fmt.Println(s) // [3 5]
- s = s[1:]
- fmt.Println(s) // [5]
- }
- func sliceLengthAndCapacity() {
- fmt.Println("\n**Slice length and capacity**")
- // A slice has both a length and a capacity.
- //
- // The length of a slice is the number of elements it contains.
- //
- // The capacity of a slice is the number of elements in the underlying array,
- // counting from the first element in the slice.
- //
- // The length and capacity of a slice s can be obtained using the expressions
- // len(s) and cap(s).
- //
- // You can extend a slice's length by re-slicing it, provided it has sufficient
- // capacity.
- s := []int{2, 3, 5, 7, 11, 13}
- printSlice(s)
- // Slice the slice to give it zero length.
- s = s[:0]
- printSlice(s)
- // Extend its length.
- s = s[:4]
- printSlice(s)
- // Try to extent beyond its capacity
- // s = s[:7] // runtime error: slice bounds out of range
- // printSlice(s)
- }
- func nilSlices() {
- fmt.Println("\n**Nil Slices**")
- // The zero value of a slice is nil.
- // A nil slice has a length and capacity of 0 and has no underlying array.
- var s []int
- fmt.Printf("slice=%v length=%v capacity=%v\n",s, len(s), cap(s))
- if s == nil {
- fmt.Println("nil!")
- }
- }
- func creatingSliceWithMake() {
- fmt.Println("\n**Creating a slice with make**")
- // Slices can be created with the built-in make function
- // This is how you create dynamically-sized arrays.
- // The "make" function allocates a zeroed array and returns a slice that refers to that array:
- a := make([]int, 5) // len(a)=5
- logSlice("a", a)
- // To specify a capacity, pass a third argument to make:
- b := make([]int, 0, 5)
- logSlice("b", b)
- c := b[:2]
- logSlice("c", c)
- d := c[2:5]
- logSlice("d", d)
- }
- func slicesOfSlices() {
- fmt.Println("\n**Slices of slices**")
- // Slices can contain any type, including other slices.
- // Create a tic-tac-toe board.
- board := [][]string{
- []string{"_", "_", "_"},
- []string{"_", "_", "_"},
- []string{"_", "_", "_"},
- }
- // The players take turns.
- board[0][0] = "X"
- board[2][2] = "O"
- board[1][2] = "X"
- board[1][0] = "O"
- board[0][2] = "X"
- for i := 0; i < len(board); i++ {
- fmt.Printf("%s\n", strings.Join(board[i], " "))
- }
- }
- func appendingToSlice() {
- fmt.Println("\n**Appending to a slice**")
- // It is common to append new elements to a slice, and so Go provides a built-in append function.
- // func append(s []T, vs ...T) []T
- // The first parameter s of append is a slice of type T, and the rest are T values to append to the slice.
- //
- // The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
- //
- // If the backing array of s is too small to fit all the given values a bigger array will be allocated.
- // The returned slice will point to the newly allocated array.
- var s []int
- printSlice(s)
- // append works on nil slices.
- s = append(s, 0)
- printSlice(s)
- // The slice grows as needed.
- s = append(s, 1)
- printSlice(s)
- // We can add more than one element at a time.
- s = append(s, 2, 3, 4)
- printSlice(s)
- }
- // Helpers
- func printSlice(s []int) {
- fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
- }
- func logSlice(s string, x []int) {
- fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap(x), x)
- }
Add Comment
Please, Sign In to add comment