Skip to content

proposal: Go 2: define slice equality #23725

@pciet

Description

@pciet

Slices should have equality defined which would allow slice types to be used as map keys and in comparison with == and !=.

An implementation proposal is that slices are compared by nil versus non-nil, length and backing array pointer, and then by the rules for array if length is equal but different arrays are pointed.

Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

Additionally self-referencing types using a slice cannot be compared, and values of map key types using a slice are copied; map types with a slice key can only be keyed by slice value.

In my experience this would have been useful for a map keyed by a path of X,Y coordinates. With Go 1 in this case a pointer to a slice was used, which means consumers of the map can do comparisons between these paths but cannot access the map using new paths without possible duplicates.

The choice of comparison by slice header vs by slice value is arbitrary and debated:

The problem is that different programs need different things for slice equality. Some want pointer equality as you suggest. Some want element comparisons, as is done for array equality. Without an obvious semantics for the operation, the language omits it entirely.

The topic is discussed here: https://groups.google.com/forum/#!topic/golang-nuts/ajXzEM6lqJI

In the first part of this golang-nuts thread one person asks for by-header while four ask for by-value. I’m in the by-value camp and I think picking one is better than having neither.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions