Skip to content

proposal: spec: add comparable w/o interfaces #49587

Description

@Code-Hex

What do I want?

  • I want a new comparable type that does not include interface{}.

Background

#49584

  • The current comparable type includes interface{}.
  • If an interface{} is passed to the function, we need to determine if it is comparable at runtime using reflect package. (to avoid panic)

I think comparable type which can only be determined at runtime, is almost the same as any type.

generics

import "reflect"

func Equal[T comparable](v1, v2 T) bool {
	if !reflect.TypeOf(v1).Comparable() {
		return false
	}
	if !reflect.TypeOf(v2).Comparable() {
		return false
	}
	return v1 == v2
}

func main() {
	v1 := interface{}(func() {})
	v2 := interface{}(func() {})
	Equal(v1, v2)
}

non-generics

import "reflect"

func Equal(v1, v2 interface{}) bool {
	if !reflect.TypeOf(v1).Comparable() {
		return false
	}
	if !reflect.TypeOf(v2).Comparable() {
		return false
	}
	return v1 == v2
}

func main() {
	v1 := interface{}(func() {})
	v2 := interface{}(func() {})
	Equal(v1, v2)
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions