Skip to content

map does not support keys of type parameter any, despite supporting any as key. affected/package: base #51384

Closed
@abligh

Description

@abligh

(go 1.18 - details at the bottom)
affected/package: base

What did you do?

Attempt to make a generic map. A simple example is at https://go.dev/play/p/odFEAA0i5uZ?v=gotip

What did you expect to see?

It is possible to have a type parameter representing any type usable for the key of a map

What did you see instead?

It is not possible to have a type parameter representing any type usable for the key of a map. Specifically the key type any cannot be used in a type parameter, whereas it is possible to use directly as a key with map[].

For instance:

type MapBool[K any] struct {
 	m map[K]bool
}

Fails because K has a missing comparable constraint.

However, if we use

type MapBool[K comparable] struct {
 	m map[K]bool
}

then

type m3 = MapBool[any]

fails because any does not implement comparable

However

type m1 = map[any]bool

works just fine.

This makes it difficult (impossible?) to implement a generic with the same flexibility as map (FWIW I was trying to make a generic based sync.map). It seems that map requiring a comparable might be overconstrained as map[] appears to be able to successfully compare interface{} (i.e. any)

What version of Go are you using (go version)?

$ go version
go1.18rc1

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/amb/Library/Caches/go-build"
GOENV="/Users/amb/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/amb/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/amb/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.18rc1"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/amb/go/src/github.com/abligh/gsyncmap/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/_r/zj8cp1n90vjgfjgm2clvqvjh0000gn/T/go-build3224811868=/tmp/go-build -gno-record-gcc-switches -fno-common"

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions