Check if two slices share the same backing array

Avatar of the author Willem Schots
8 Jul, 2023 (Updated 20 Jul, 2023)
~2 min.
RSS

There is no safe way to get a reference to the underlying array of a slice. So how do you check if two slices share the same array?

If the slices overlapped we could look for an element with the same memory address (which we can get using the & operator).

Since there is no guarantee the slices overlap we need to do a bit more work: we need to re-slice them up to their capacity. This gives us two new slices that will overlap if they share the same backing array.

We can then compare the addresses of their last elements to check if they share a backing array.

The diagram shows this procedure.

Two non-overlapping slices code and fruits that share the same array a
Re-slice both slices up to their capacities.
Check the addresses of their last elements using the & operator.

And the example code below shows a generic SameArray function that implements this check.

main.go
package main

import (
	"fmt"
)

func main() {
	a := [6]string{"", "🍕", "🍔", "🍒", "🍋", ""}
	food := a[1:3]
	fruits := a[3:5]
	other := []string{"", ""}

	fmt.Println("do food and fruits share an array?", SameArray(food, fruits))
	fmt.Println("do food and other share an array?", SameArray(food, other))
	fmt.Println("do fruits and other share an array?", SameArray(fruits, other))
}

// SameArray checks if two slices reference the same backing array.
func SameArray[T any](s1, s2 []T) bool {
	cap1 := cap(s1)
	cap2 := cap(s2)

	// nil slices will never have the same array.
	if cap1 == 0 || cap2 == 0 {
		return false
	}

	// compare the address of the last element in each backing array.
	return &s1[0:cap1][cap1-1] == &s2[0:cap2][cap2-1]
}

Get my free newsletter every second week

Used by 500+ developers to boost their Go skills.

"I'll share tips, interesting links and new content. You'll also get a brief guide to time for developers for free."

Avatar of the author
Willem Schots

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Twitter/X, LinkedIn or Mastodon.

Thanks for reading!