DEV Community

Mohammad Gholami
Mohammad Gholami

Posted on

5

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay