This is the 16th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Create a slice

  • Directly to create

    var hobby = []string{"Calligraphy"."Basketball"."Table tennis"."Swimming"."Fitness"."Learning"."Reading"."coding"}
    fmt.Println(hobby) // [Calligraphy basketball Table tennis swimming fitness learning reading coding]
    Copy the code
  • Array based creation

    front := [...]string{"html"."css"."javascript"."typescript"."vue"."react"."Wechat Mini Program"}
    // Generate a slice based on the array with "slice name [start:end]"
    frontEnd := front[:]
    fmt.Println(frontEnd) // [HTML CSS javascript typescript vue react]
    Copy the code

    Go’s rule of slicing: the number passed in is the index of the element;

  • When passed only at the beginning but not at the end, it starts with the index of the passed element and ends with the last element of the array (slice)

    front := [...]string{"html"."css"."javascript"."typescript"."vue"."react"."Wechat Mini Program"}
    
    start := front[2:]
    fmt.Println(start) // javascript typescript vue react
    Copy the code
  • When passed only the end but not the start, it starts with the index of the first element of the array (slice) and subtracts 1 from the passed end index

    front := [...]string{"html"."css"."javascript"."typescript"."vue"."react"."Wechat Mini Program"}
    
    end := front[:3]
    fmt.Println(end) 
    Copy the code
  • When neither the start index nor the end index is passed, all elements of the entire array (slice) are included

    front := [...]string{"html"."css"."javascript"."typescript"."vue"."react"."Wechat Mini Program"}
    
    frontEnd := front[:] // Generate a slice based on the array with "slice name [start:end]"
    fmt.Println(frontEnd) // [HTML CSS javascript typescript vue react]
    Copy the code
  • Create using the make function

    create := make([]string.4) // Both length and capacity are 4
    create1 := make([]string.4.6) // The length is 4 and the capacity is 6
    Copy the code

    The capacity can be omitted when the length and capacity are equal

You can think of a slice as a simple encapsulation of an array. Since there must be an array in the underlying data structure of each slice, an array is also called the underlying array of a slice. Slices can be thought of as references to successive fragments of an array, either partial or full. Use len() to get the length of the slice, and cap() to get the size of the capacity

The basic operation of slice

The built-in function append() can be used to add, delete, replace and copy slices

new

New uses the append() method to add elements, returning a new slice and assigning to the originally declared slice

create := make([]string.4) // The default length and capacity are 4
create = append(create, "Basketball")
create = append(create, "Calligraphy")
create = append(create, "Swimming")
create = append(create, "Fitness")
create = append(create, "Reading")
fmt.Println(create) // Basketball Calligraphy Swimming fitness reading
fmt.Printf("Create length: %d\n".len(create)) / / 9
fmt.Printf("Create has capacity: %d\n".cap(create)) / / 16
Copy the code

Slice expansion does not change the underlying array of the original slice, but generates a larger underlying array, and then copies the elements in the original slice and the new elements into the new slice. In general, we can simply assume that the volume of the new slice is twice that of the old slice; If the length of the original slice is greater than 1024, the capacity of the new slice is 1.25 times that of the old one. If the new length exceeds the size of the original slice, appending elements to it using the append() function will not cause expansion

delete

var hobby = []string{"Calligraphy"."Basketball"."Table tennis"."Swimming"."Fitness"."Learning"."Reading"."coding"}	
var favorite = append(hobby[:2], hobby[3:]...).// In this way, the "ping pong" item is deleted
fmt.Println("favorite:", favorite) // Favorite: calligraphy, basketball, swimming, fitness, reading
Copy the code

Note the use of three dots (…) Because when using the append() method, you need to add specific individual elements, whereas hobby is a slice, so Go uses three dots (…) Break up a slice into individual elements so that you can use the append() method

Replace/Update

var hobby = []string{"Calligraphy"."Basketball"."Table tennis"."Swimming"."Fitness"."Learning"."Reading"."coding"}
hobby[0] = "Hard pen calligraphy"
fmt.Println(hobby) // [Hard pen calligraphy basketball table tennis swimming fitness learning reading coding]
Copy the code

copy

In practice, it is often necessary to create entirely new slices based on the slices of gay friends; To copy a slice, you must create a slice that contains the entire list; The method is to omit the starting index ([:]), and then Go creates a slice that starts with the first element and ends with the slice element of the last element, that is, to copy the whole slice

  • Copy by omitting the starting position

    This is the same as creating slices based on arrays

    front := [...]string{"html"."css"."javascript"."typescript"."vue"."react"."Wechat Mini Program"}
    frontEnd := front[:]
    Copy the code
  • Copy using the built-in function

    Go’s built-in function copy, which copies contents from one array slice to another; If two array slices are added with different sizes, the smaller array slice is copied

traverse

var hobby = []string{"Calligraphy"."Basketball"."Table tennis"."Swimming"."Fitness"."Learning"."Reading"."coding"}

for index, item := range hobby {
  fmt.Printf("Value for index %d: %s \n", index, item)
}
Copy the code

In the For rnage loop in Go, a copy of the value is always used instead of the element being traversed, i.e. the value in the for range loop is a copy of the value, not the element itself