Copying slice over itself

301 views
Skip to first unread message

Deepak Jois

unread,
Sep 7, 2017, 1:54:16 AM9/7/17
to golan...@googlegroups.com
Hi

Pls look at this code: https://play.golang.org/p/QfQOo1iyp4

I am copying a slice over itself. How does it work internally? Does
the copy operation optimise for this, and not perform any copying in
this case?

I have to deal with a situation where I get a slice reference back
from a function, and it is possible that it points to the same slice
that I am trying to copy it into. It would be nice if the copy
operation in that case is a no-op, but I don’t want to assume that is
the case.

Deepak

dja...@gmail.com

unread,
Sep 7, 2017, 3:41:58 AM9/7/17
to golang-nuts
Hi,
Just check if backing array are same before copying:
https://play.golang.org/p/MSqs-jRkSO

Rob Pike

unread,
Sep 7, 2017, 4:17:59 AM9/7/17
to dja...@gmail.com, golang-nuts
That test is only sufficient if the zeroth elements in the two slices
are at the same address, which is often not true:
https://play.golang.org/p/TH53Pxt5Do

Two slices sharing an array will, however, share their last element.
Here is a better test, but this is pretty magical stuff:
https://play.golang.org/p/SZgpCh9D-l Note that it cannot tell whether
the elements actually overlap, but you can do that too if you work a
little harder - again, capacity is the key. I leave that as an
exercise.

All that aside, copying a slice to itself is not a no-op
computationally (it will execute the copy) but the slice will not be
modified.

-rob
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

peterGo

unread,
Sep 7, 2017, 6:54:03 AM9/7/17
to golang-nuts
Rob,


"Two slices sharing an array will, however, share their last element.
Here is a better test, but this is pretty magical stuff:
https://play.golang.org/p/SZgpCh9D-l"

    a := []int{0, 1, 2, 3, 4, 5, 6, 7}
    s := a[1:3:5]

https://play.golang.org/p/Q8I3Vein5n

Peter

peterGo

unread,
Sep 7, 2017, 7:03:33 AM9/7/17
to golang-nuts
Deepak Jois,

Consider this case:

The Go Programming Language Specification https://golang.org/ref/spec

Slice expressions https://golang.org/ref/spec#Slice_expressions

Full slice expressions

For an array, pointer to array, or slice a (but not a string), the primary expression

    a[low : high : max]

constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low. Only the first index may be omitted; it defaults to 0.

Peter
Reply all
Reply to author
Forward
0 new messages