Why can't I duplicate a slice with `copy()`?

前端 未结 6 704
情书的邮戳
情书的邮戳 2021-01-29 23:02

I need to make a copy of a slice in Go and reading the docs there is a copy function at my disposal.

The copy built-in function copies elements from a so

6条回答
  •  长情又很酷
    2021-01-29 23:07

    NOTE: This is an incorrect solution as @benlemasurier proved

    Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

    package main
    
    import "fmt"
    
    func main() {
        var foo = []int{1, 2, 3, 4, 5}
        fmt.Println("foo:", foo)
        var bar = append(foo)
        fmt.Println("bar:", bar)
        bar = append(bar, 6)
        fmt.Println("foo after:", foo)
        fmt.Println("bar after:", bar)
    }
    

    Outputs this:

    foo: [1 2 3 4 5]
    bar: [1 2 3 4 5]
    foo after: [1 2 3 4 5]
    bar after: [1 2 3 4 5 6]
    

提交回复
热议问题