Skip to content

maps: add Same func #78456

Description

@adonovan

Update: latest API proposal at #78456 (comment).

Background: In Go, maps are references to hash tables. Because hash tables are mutable, identity is important. All mutations applied to one reference are observed by all identical references. Two maps are identical if they were created by the same make(M) call or map literal M{...}.

The language does not provide a direct means of testing whether two maps are identical. Maps are not comparable, to avoid the confusion that would arise when reading x == y: some might think it compares the entries of the map, while others assume it compares only the references. Nonetheless it is often useful to query whether two maps are identical. For example, the implementation of a z = union(x, y) function might be able to take a short cut if x and y refer to the same hash table.

It is possible to test whether two maps are identical using reflection: reflect.ValueOf(x).UnsafePointer() == reflect.ValueOf(y).UnsafePointer(); alternatively you can compare the reflect.Values directly. But both of these compile to rather inefficient code; also the operation is totally safe, so users shouldn't have to reach for reflect and unsafe.

Proposal: We propose to add the maps.Identical function, which reports whether two maps are identical references.

package maps

// Identical reports whether two maps refer to the same data structure.
//
// Note: many algebraic shortcuts based on Identical(x, y) are invalid for NaN elements.
func Identical[MX ~map[K]VX, MY ~map[K]VY, K comparable, VX, VY any](x MX, y MY) bool {
	type pointer = unsafe.Pointer
	return *(*pointer)(pointer(&x)) == *(*pointer)(pointer(&y))
}

The function body compiles down to a CMP instruction.

Metadata

Metadata

Assignees

Labels

LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposalProposal-Accepted

Type

No type

Projects

Status
Accepted

Relationships

None yet

Development

No branches or pull requests

Issue actions