Three ways of using golang slices and their differences



Slice is a more convenient, flexible and powerful data structure based on array. The slice does not store any elements, but just a reference to an existing array.

Three ways and detailed cases

① Define a slice, and then let the slice refer to an array that has been created

package main
import (
func main() {
    var arr [5]int = [...]int {1, 2, 3, 4, 5}
    var slice = arr[1:3]
    fmt.Println("arr=", arr)
    fmt.Println("slice=", slice)
    fmt.Println("slice len", len(slice))
    fmt.Println("slice cap", cap(slice))

② Create slices with make

Basic syntax: VAR slice name [] type = make ([], len, [cap]); Parameter Description: type is the data type, len is the size, and cap is the slice capacity (the capacity must be > = length)

You can specify the slice size and capacity by creating slices by making

If no value is assigned to each element of the slice, the default values (int, float = > 0, string = > “”, bool = > false) will be used

The array corresponding to the slice created by Rongguo make is maintained by the bottom layer of make and is invisible to the outside, that is, each element can only be accessed through slice

package main
import (
func main() {
    var slice []float64 = make([]float64, 5, 10)
    //No value is given. The default value is 0
    fmt.Println(slice)  //[0 0 0 0 0]
    slice[1] = 5
    slice[3] = 10  
    fmt.Println(slice)  //[0 5 0 10 0] 
    fmt. Println ("slice size:", len (slice)) // slice size: 5
    fmt. Println ("slice capacity:", cap (slice)) // slice capacity: 10

③ Define a slice and directly specify a specific array. The principle is similar to make

package main
import (
func main() {
    var slice []string = []string{"zhangsan", "lisi", "wangwu"}
    fmt.Println("slice=", slice) //slice= [zhangsan lisi wangwu]
    fmt.Println("slice len", len(slice)) //slice len 3
    fmt.Println("slice cap", cap(slice)) //slice cap 3

The difference between the first and the second

The first way is to directly reference the array, which is pre-existing and visible to programmers

The second way is to create slices through make. Make will also create an array. The slices are maintained at the bottom and not visible to programmers

Supplement: piecemeal cases

package main
import "fmt"
func main() { 
    //Unlike arrays, the length of slices is variable.
    //We can use the built-in function make to create a slice whose length is not zero
    //Here we create a slice with a length of 3 to store the string, the slice element
    //The default value is zero, which is "" for strings.
    s := make([]string, 3)
    fmt.Println("emp:", s)
    //You can use the same method as arrays to set or get element values
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)
    fmt.Println("get:", s[2])
    //You can use the built-in function len to get the length of the slice
    fmt.Println("len:", len(s))
    //Slicing also has some functions that arrays do not have.
    //For example, we can use the built-in function append to append a value to the slice, and then
    //Returns a slice with a new slice element.
    //Note that the append function does not change the original slice, but generates a new slice,
    //We need to use the original slice to receive the new slice
    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd:", s)
    //In addition, we can copy elements from one slice to another
    //The following example creates a new slice with the same length as the slice s
    //Then use the built-in copy function to copy the elements of s into C.
    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy:", c)
    //Slicing also supports a slicing operation "slice [low: high]"
    //The new slice obtained contains the element 'slice [low], but does not contain' slice [high] '
    //The following example is to take a new slice. The elements include "s [2]," s [3], "s [4]".
    l := s[2:5]
    fmt.Println("sl1:", l)
    //If low is omitted, it starts from 0 by default, excluding the "slice [high]" element
    l = s[:5]
    fmt.Println("sl2:", l)
    //If high is omitted, it defaults to len (slice), including the "slice [low]" element
    l = s[2:]
    fmt.Println("sl3:", l)
    //We can declare and initialize a slice at the same time
    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)
    //We can also create multidimensional slices. Unlike arrays, the length of slice elements is also variable.
    twoD := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoD[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoD[i][j] = i + j
    fmt.Println("2d: ", twoD)


emp: [  ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.

Recommended Today

Explanation of websocket heartbeat reconnection

Recently, websocket has been used in the development of applet. The applet provides corresponding native API, which is different from H5 API. Therefore, some mature class libraries of popular H5 are difficult to use, and the native API has some defects, so it implements a set of heartbeat reconnection mechanism by itself. First, let’s briefly […]