SoFunction
Updated on 2025-03-05

Three ways to use golang slices and explanations

concept

Slices are more convenient, flexible and powerful data structures built on arrays. A slice does not store any elements but is just a reference to an existing array.

Three methods and detailed cases

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

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

②Create slices by 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 (capacity must be >= length)

Create slices by making to specify the size and capacity of slices

If no values ​​are assigned to the various elements of the slice, the default values ​​(int, float=>0, strint=>"", bool=>false) will be used.

The corresponding array of slices created by Rongguo make method is maintained by make and is not visible to the outside world, that is, they can only access various elements through slices.

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

③ Define a slice, directly specify the specific array, and use principle is similar to make

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

The difference between the first and the second

The first method is to directly refer to the array, which exists in advance and can be seen by programmers

The second way is to create slices through make. Make will also create an array, which is maintained by slices at the bottom and cannot be seen by programmers.

Supplement: Scrap cases

package main
import "fmt"
func main() { 
    // Unlike arrays, the length of the slice is variable.    // We can use the built-in function make to create a slice with a length of non-zero    // Here we create a slice and slice element with length 3, storing strings    // The default is zero value, which is "" for strings.    s := make([]string, 3)
    ("emp:", s)
 
    // You can use the same method as an array to set element values ​​or get element values    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    ("set:", s)
    ("get:", s[2])
 
    // You can use the built-in function len to get the length of the slice    ("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 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 this new slice    s = append(s, "d")
    s = append(s, "e", "f")
    ("apd:", s)
 
    // In addition, we can copy elements from one slice to another slice    // The following example is to create a new slice with the same length as the slice s    // Then use the built-in copy function to copy the element of s into c.    c := make([]string, len(s))
    copy(c, s)
    ("cpy:", c)
 
    // Slices also support a slice 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, with elements including "s[2]", "s[3]", "s[4]".    l := s[2:5]
    ("sl1:", l)
 
    // If low is omitted, the default starts from 0, and the "slice[high]" element is not included    l = s[:5]
    ("sl2:", l)
 
    // If high is omitted, the default is len(slice), including the "slice[low]" element    l = s[2:]
    ("sl3:", l)
 
    // We can declare and initialize a slice at the same time    t := []string{"g", "h", "i"}
    ("dcl:", t)
 
    // We can also create multi-dimensional slices. Unlike arrays, the length of the 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
        }
    }
    ("2d: ", twoD)
}

result

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 personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.