Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clone func used since go 1.21 #947

Merged
merged 1 commit into from
May 30, 2024
Merged

Conversation

ucwong
Copy link
Contributor

@ucwong ucwong commented May 26, 2024

No description provided.

@ucwong ucwong marked this pull request as ready for review May 26, 2024 14:12
@anacrolix
Copy link
Owner

I don't think this is the same behaviour as the original. You need to be cloning the internal slices.

@ucwong
Copy link
Contributor Author

ucwong commented May 30, 2024

I don't think this is the same behaviour as the original. You need to be cloning the internal slices.

import (
        "fmt"
        "golang.org/x/tools/go/packages"
)

func main() {
        original := [][]string{
                {"a", "b"},
                {"c", "d"},
        }

        // Deep copy using slices.Clone
        cloned := slices.Clone(original)

        // Modify the original
        original[0][0] = "X"

        fmt.Println("Original:", original) // Output: [[X, "b"], ["c", "d"]]
        fmt.Println("Cloned:", cloned)  // Output: [['a', 'b'], ['c', 'd']]
}

In this example:

original is a slice of slices containing two inner slices of strings.
cloned is created using slices.Clone(original), resulting in a deep copy.
Modifying original doesn't affect cloned because they are independent copies.
Key Points:

slices.Clone is available in Go 1.21 and later.
For earlier versions, you can use the golang.org/x/exp/slices package (experimental).
This approach is efficient and avoids manual copying loops.
I hope this explanation clarifies how slices.Clone works with [][]string in Go!

@anacrolix anacrolix merged commit d196bf9 into anacrolix:master May 30, 2024
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants