golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.85k stars 17.65k forks source link

proposal: cmp: Equal #70161

Open jimmyfrasche opened 19 hours ago

jimmyfrasche commented 19 hours ago

Proposal Details

I find myself writing this a lot lately. Sometimes multiple times in a module because I don't want to export it or bother with creating internal/ packages just for this.

package cmp

func Equal[T comparable](a, b T) bool {
  return a == b
}

This comes up whenever you have Op and OpFunc where the latter variant takes an equality function. The body of Op just calls OpFunc with some local copy of the proposed.

Even with the shortest possible syntax proposed in #21498 this would still be (a, b) => a == b vs cmp.Equal[T] and T would often be inferred as this is basically always used as the argument to a function.

gabyhelp commented 19 hours ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

ianlancetaylor commented 18 hours ago

A minor nit: in order to correspond to cmp.Compare, the implementation in the cmp package should be something like

func Cmp[T comparable](a, b T) bool {
    if isNaN(a) && isNaN(b) {
        return true
    }
    return a == b
}