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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More