DEV Community

Mohammad Gholami
Mohammad Gholami

Posted on

Re-slicing in Golang

What is re-slicing in Golang?

If you create a slice in Golang, you can create another slice from the original slice using [i:j] notation that is called re-slicing. The new slice starts from the i index going up to the j index without including the j index.

Re-slicing is so simple:

s1 := []int{1, 5, 7, 12, 9}
reslice := s1[1:3]
Enter fullscreen mode Exit fullscreen mode

Be careful: Slices in Go are always passed by reference.

So, if you create a new slice by re-slicing a slice and modify it, the original slice also will be charged. Look at the example:

package main

import (
    "fmt"
)

func main() {
    s1 := []int{1, 5, 7, 12, 9}
    reslice := s1[1:3]

    fmt.Println(s1) // [1 5 7 12 9]
    fmt.Println(reslice) // [5 7]

    // make some changes
    reslice[0] = 128
    reslice[1] = 256

    fmt.Println(s1) // [1 128 256 12 9]
    fmt.Println(reslice) // [128 256]
}

Enter fullscreen mode Exit fullscreen mode

As you can see, the original slice also is updated.

Top comments (0)