跳转至

检查两个切片的底层数组是否相同

参考:Check if slices share the same backing array in Go/Golang (willem.dev)

思路:比较底层数组最后一个元素的地址。

// 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]
}