Consider this example:
sliceA := make([]byte, 10)
sliceB := make([]byte, 10)
// sliceA and sliceB are referencing different memory,
// witch eventually may contain same data
sliceC := sliceA[:]
// sclieC references same memory as sliceA
sliceD := sliceA[1:2]; sliceE := sliceA[4:5]
// assert that sliceD and sliceE share same block of memory
Is there any way to check that 2 slices are references (or not) to the same memory?
EDIT
The slices that I want to compare might not point to the same segment of underlying block of memory.
Two non nil instances, a and b, of type []T, share the same backing array iff
&a[cap(a)-1] == &b[cap(b)-1]
Note that it may be necessary to reslice a and or b before the test.
You can test the addresses by importing "reflect"
:
same := reflect.ValueOf(sliceA).Pointer() == reflect.ValueOf(sliceC).Pointer()
Example :
package main
import (
"fmt"
"reflect"
)
func main() {
sliceA := make([]byte, 10)
sliceC := sliceA[1:]
sliceD := sliceA[1:]
fmt.Println(reflect.ValueOf(sliceC).Pointer() == reflect.ValueOf(sliceD).Pointer())
}
This tests the position of the slice's start, not just the underlying array.
@canni's question and @jnml's and @dystroy's answers are confused and confusing.
Here's the simple version.
package main
import (
"fmt"
"reflect"
)
func main() {
sliceA := make([]byte, 10)
sliceD := sliceA[1:2]
sliceE := sliceA[4:5]
// assert that sliceD and sliceE share same block of memory
canni := true
jnml := &sliceD[:cap(sliceD)][cap(sliceD)-1] == &sliceE[:cap(sliceE)][cap(sliceE)-1]
dystroy := reflect.ValueOf(sliceD).Pointer() == reflect.ValueOf(sliceE).Pointer()
// true true false
fmt.Println(canni, jnml, dystroy)
}
Output:
true true false