English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang function & method

Golang struct

Golang slice & array

Golang string(String)

Golang pointer

Golang interface

Golang concurrency

Golang exception(Error)

Golang other items

Go Language Slice (Slice)

In Go language, slices are moreArrayMore powerful, flexible, convenient, and lightweight data structure. Slice is a variable-length sequence used to store elements of the same type, and it does not allow the storage of different types of elements in the same slice. It is like an array with index values and length, but the size of the slice can be adjusted, unlike the fixed size of an array. Internally, slices and arrays are interconnected, and slices are references to the underlying array. It allows the storage of duplicate elements.The first index position in the slice is always 0, while the last index position will be (slice length - 1).

Declaration of slice

The declaration of a slice is like an array, but it does not contain the size of the slice. Therefore, it can grow or shrink as needed.

Create a slice. This function takes three parameters, namely type, length, and capacity. Here, the capacity value is optional. It allocates the size of the underlying array equal to the given capacity and returns a slice that references the underlying array. Usually, the make() function is used to create an empty slice. Here, the empty slice is those slices that contain references to empty arrays.

[]T
or
[]T{}
or
[]T{value1, value2, value3, ...value n}

Here, T is the type of the element. For example:

var my_slice[]int

Composition of slice

A slice contains three components:

  • Pointer:Pointer is used to point to the first element of the array that can be accessed through the slice. Here, the pointed element does not have to be the first element of the array.

  • Length:Length is the total number of elements existing in the array.

  • Capacity:Capacity represents the maximum size that can be expanded.

Let's discuss all these components with examples:

//slice
package main
Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
func main() {
    //Create an array
    arr := [7string{"this", "is", "Golang", "basic", "tutorial", "online", "www.oldtoolbag.com"}
    //Display the array
    fmt.Println("Array:", arr)
    //Create a slice
    myslice := arr[1:6]
    //Display the slice
    fmt.Println("Slice:", myslice)
    //Display the length of the slice
    fmt.Printf("Slice length: %d", len(myslice))
    //Display the capacity of the slice
    fmt.Printf("\nSlice capacity: %d", cap(myslice))
}

Output:

Array: [this is the Golang Basic Tutorial Online www.oldtoolbag.com]
Slice: [is the Golang Basic Tutorial Online]
Slice length: 5
Slice capacity: 6

Usage explanation:In the above example, we create a slice from the given array. Here, the pointer of the slice points to index1, because the lower bound of the slice is set to1, so it starts accessing elements from index1The length of the slice is5, indicates the total number of elements in the slice5, while the slice6The capacity represents the maximum number of elements that can be stored6elements.

How to create and initialize slices?

In Go language, you can create and initialize slices in the following ways:

  • Use slice literals:You canUse slice literalsCreate a slice. The creation of a slice literal is similar to an array literal, but there is a difference, that is, you are not allowed to specify the size of the slice within the square brackets []. As shown in the following example, the right side of the expression is a slice literal.

    var my_slice_1 = []string{"w3codeboxs "for", "w3codeboxs ""

    trueRemember, when you use string literals to create a slice, it first creates an array and then returns a slice reference to it.

    // Use slice literals to create slices
    package main
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
    func main() {
        //Create a slice using the var keyword
        var my_slice_1 = []string{"w3codeboxs "for", "w3codeboxs ""
        fmt.Println("My Slice 1my_slice_1)
        //Create a slice
        //Using shorthand declaration
        my_slice_2 := []int{12, 45, 67, 56, 43, 34, 45}
        fmt.Println("My Slice 2my_slice_2)
    }

    Output:

    My Slice 1: [w3codeboxs for w3codeboxs]
    My Slice 2New slice12 45 67 56 43 34 45]
  • Using an array:We have already knownSlices are references to arrays,Therefore, you can create a slice based on the given array. To create a slice from the given array, you first need to specify the lower and upper bounds, which means the slice can start getting elements from the lower bound to the upper bound in the array. It does not include the elements starting from the upper bound. As shown in the following example:

    Create a slice. This function takes three parameters, namely type, length, and capacity. Here, the capacity value is optional. It allocates the size of the underlying array equal to the given capacity and returns a slice that references the underlying array. Usually, the make() function is used to create an empty slice. Here, the empty slice is those slices that contain references to empty arrays.

    array_name[low:high]

    This syntax will return a new slice.

    trueThe default lower bound is 0, and the default upper bound is the total number of elements existing in the given array.

  • //Create a slice from an array
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create an array
        arr := [4]string{"w3codeboxs "for", "w3codeboxs "GFG" 
      
        //Create a slice from the given array 
        var my_slice_1 = arr[1:2] 
        my_slice_2 := arr[0: 
        my_slice_3 := arr[:2] 
        my_slice_4 := arr[: 
      
        //Display result
        fmt.Println("My array: "arr) 
        fmt.Println("My Slice 1: "my_slice_1) 
        fmt.Println("My Slice 2: "my_slice_2) 
        fmt.Println("My Slice 3: "my_slice_3) 
        fmt.Println("My Slice 4: "my_slice_4) 
    }

    Output:

    My array: [w3codeboxs for w3codeboxs GFG]
    My Slice 1: [for]
    My Slice 2: [w3codeboxs for w3codeboxs GFG]
    My Slice 3: [w3codeboxs for]
    My Slice 4: [w3codeboxs for w3codeboxs GFG]
  • Using an existing slice:You can also create a slice from the given slice. To create a slice from the given slice, you first need to specify the lower and upper bounds, which means the slice can start getting elements from the lower bound to the upper bound in the given slice. It does not include the elements starting from the upper bound. As shown in the following example:

    Create a slice. This function takes three parameters, namely type, length, and capacity. Here, the capacity value is optional. It allocates the size of the underlying array equal to the given capacity and returns a slice that references the underlying array. Usually, the make() function is used to create an empty slice. Here, the empty slice is those slices that contain references to empty arrays.

    slice_name[low:high]

    This syntax will return a new slice.

    trueThe default lower bound is 0, and the default upper bound is the total number of elements existing in the given slice.

    //Create a slice from an array
    package main
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
    func main() {
        //Create a slice
        oRignAl_slice := []int{90, 60, 40, 50, 34, 49, 30}
        //Create a slice from the given slice
        var my_slice_1 = oRignAl_slice[1:5]
        my_slice_2 := oRignAl_slice[0:
        my_slice_3 := oRignAl_slice[:6]
        my_slice_4 := oRignAl_slice[:
        my_slice_5 := my_slice_3[2:4]
        //Display result
        fmt.Println("Original slice:", oRignAl_slice)
        fmt.Println("New slice" 1my_slice_1)
        fmt.Println("New slice" 2my_slice_2)
        fmt.Println("New slice" 3my_slice_3)
        fmt.Println("New slice" 4my_slice_4)
        fmt.Println("New slice" 5my_slice_5)
    }

    Output:

    :"90 60 40 50 34 49 30]
    Original slice: [ 1New slice60 40 50 34]
    Original slice: [ 2New slice90 60 40 50 34 49 30]
    Original slice: [ 3New slice90 60 40 50 34 49]
    Original slice: [ 4New slice90 60 40 50 34 49 30]
    Original slice: [ 5New slice40 50]
  • : [Use make() function:You can also use the go library providedmake() function

    Create a slice. This function takes three parameters, namely type, length, and capacity. Here, the capacity value is optional. It allocates the size of the underlying array equal to the given capacity and returns a slice that references the underlying array. Usually, the make() function is used to create an empty slice. Here, the empty slice is those slices that contain references to empty arrays.

    Syntax:
    //Use make function
    package main
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
    func main() {
        //func make([]T, len, cap) []T7Create another array of
        //Create an array of size4
        //and return a reference to the array
        //Use make function
        var my_slice_1 = make([]int, 4, 7)
        fmt.Printf("Slice 1 = %v, 
    length = %d, 
    capacity = %d
    ", my_slice_1, len(my_slice_1), cap(my_slice_1))
        //Cut this array into7Create another array of
        //and return a reference to the array
        //Use make function
        var my_slice_2 = make([]int, 7)
        fmt.Printf("Slice 2 = %v, 
    length = %d, 
    capacity = %d
    ", my_slice_2, len(my_slice_2), cap(my_slice_2))
    }

    Output:

    Slice 1 = [0 0 0 0], 
    length = 4, 
    capacity = 7
    Slice 2 = [0 0 0 0 0 0 0], 
    length = 7, 
    capacity = 7

How to traverse a slice?

You can traverse the slice in the following way:

  • Use for loop:This is the simplest way to iterate over a slice, as shown in the following example:

    // For loop iteration of the slice
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create a slice
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
        //Use for loop to iterate
        for e := 0; e < len(myslice); e++ 0}, 
            fmt.Println(myslice[e]) 
        } 
    }

    Output:

    This
    is
    the
    tutorial
    of
    Go
    language
  • In the for loop, use the range:It allows you to iterate over the slice using the range in the for loop. When using range in the for loop, you can obtain both the index and the element value, as shown in the example:

    //In the for loop, use the range of the slice
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create a slice
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
            //Iterate through a slice
            //Using range in a for loop
        for index, ele := range myslice { 
            fmt.Printf("Index = %d and element = %s\n", index+3, ele) 
        } 
    }

    Output:

    Index = 3 and element = This
    Index = 4 and element = is
    Index = 5 and element = the
    Index = 6 and element = tutorial
    Index = 7 and element = of
    Index = 8 and element = Go
    Index = 9 and element = language
  • Using a blank identifier in a for loop: In a for loopIn a range, if you do not want to get the index value of the element, you can use a blank identifier (_), as shown in the following example:

    //Using range in a for loop without an index 
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create a slice 
        myslice := []string{"This", "is", "the", "tutorial", "of", "Go", "language"} 
      
            //Iterate through a slice
            //Using range in a for loop
            //No index
        for _, ele := range myslice { 
            fmt.Printf("Element = %s\n", ele) 
        } 
    }

    Output:

    Element = This
    Element = is
    Element = the
    Element = tutorial
    Element = of
    Element = Go
    Element = language

Key points about slices

  1. Zero-valued slice:In Go language, it allows you to create a zero-valued slice that does not contain any elements. Therefore, the capacity and length of this slice are 0. A nil slice does not contain an array reference, as shown in the following example:

    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        // Create a zero-valued slice
        var myslice []string 
        fmt.Printf("Length = %d\n", len(myslice)) 
        fmt.Printf("Capacity = %d ", cap(myslice)) 
      
    }

    Output:

    Length = 0
    Capacity = 0
  2. Modify Slice:As we already know that slices are reference types, they can reference the underlying array. Therefore, if we change some elements in the slice, the change should also occur in the referenced array. In other words, if you make any changes to the slice, the changes will also be reflected in the array, as shown in the following example:

    //How to modify a slice
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create a zero-valued slice
        arr := [6]int{55, 66, 77, 88, 99, 22} 
        slc := arr[0:4] 
      
        //Before Modification
      
        fmt.Println("Original_Array: ", arr) 
        fmt.Println("Original_Slice: ", slc) 
      
        //Modified 
        slc[0] = 100 
        slc[1] = 10New_Slice: [[ 
        slc[2] = 10New_Slice: [[ 
      
        fmt.Println("\nNew_Array: ", arr) 
        fmt.Println("New_Slice: ", slc) 
    }

    Output:

    Original_Array:  [55 66 77 88 99 22]
    Original_Slice:  [55 66 77 88]
    New_Array:  [100 10New_Slice: [[ 10New_Slice: [[ 88 99 22]
    ]]100 10New_Slice: [[ 10New_Slice: [[ 88]
  3. 00Slice comparison:operator checks if the given slice exists.In the slice, you can only useoperator checks if the given slice exists.==

    //operator under the help of comparing two slices will throw an error, as shown in the following example:
    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //Create a slice
        Create multi-dimensional slices1 := []int{12, 34, 56} 
        Determine if the slice is zero2 var s
      
            //[]int
            //If you try to run this comment
        /*Create multi-dimensional slices3:= []int{23, 45, 66} 
          Check if the given slice is nil1The code compiler will give an error3) 
        */
      
        //==s
        Check if the given slice is nil1 fmt.Println(s 
        Check if the given slice is nil2 fmt.Println(s 
    }

    Output:

    == nil)
    false

    trueNote:If you want to compare two slices, please use loop range matching each element, or you can useDeepEqual

  4. Functions.Multi-dimensional slices:

    package main 
      
    Multi-dimensional slices are similar to multi-dimensional arrays, but slices do not contain sizes.
      
    func main() { 
      
        //},
        Create multi-dimensional slices1 import \12, 34{ 
            0},56, 47{ 
            0},29, 4:= [][]int{{ 
            0},46, 78{ 
        } 
      
        //Accessing multi-dimensional slices
        fmt.Println("Slice 1 : ", s1) 
      
        //}, 
        Create multi-dimensional slices2 s 
            codeboxs", "for"},3:= [][]string{ 
            codeboxs", "for"},3codeboxs", "GFG"}, 
            []string{"gfg", "w3codebox"}, 
        } 
      
        //Accessing multi-dimensional slices
        fmt.Println("Slice 2 : ", s2) 
      
    }

    Output:

    Slice 1 : [[12 34] [56 47] [29 40] [46 78]]
    Slice 2 : [[w3codeboxs for] [w3codeboxs GFG] [gfg w3codebox]]
  5. Slice sorting:In Go language, elements existing in a slice can be sorted. The standard library of Go language provides the sort package, which includes functions for sorting slices of int, float64Different types of sorting methods for sorting string slices. These functions always sort the slices in ascending order of available elements.

    //Elements existing in the slice
    package main 
      
    import ( 
        "fmt"
        "sort"
    ) 
      
    func main() { 
      
        //Create a slice
        slc1 := []string{"Python", "Java", "C#", "Go", "Ruby"} 
        slc2 := []int{45, 67, 23, 90, 33, 21, 56, 78, 89} 
      
        fmt.Println("Before sorting:") 
        fmt.Println("Slice 1: ", slc1) 
        fmt.Println("Slice 2: ", slc2) 
      
        //Sorting functions for slices
        sort.Strings(slc1) 
        sort.Ints(slc2) 
      
        fmt.Println("\nSorted after:") 
        fmt.Println("Slice 1: ", slc1) 
        fmt.Println("Slice 2: ", slc2) 
      
    }

    Output:

    Before sorting:
    Slice 1: C# Go Java Python Ruby
    Slice 2:  [45 67 23 90 33 21 56 78 89]
    Sorted:
    Slice 1: C# Go Java Python Ruby
    Slice 2:  [21 23 33 45 56 67 78 89 90]