generics: can I require "comparable" together with some methods?

142 views
Skip to first unread message

Jochen Voss

unread,
Feb 17, 2023, 6:33:46 PM2/17/23
to golang-nuts
Hello,

I'm trying to write a generic function like the following (simplified) one:

type V interface {
    comparable // (1)
    SomeMethod(V)
}

func Test[val V](x val) {
    m := make(map[val]int) // (2)
    // uses a x as key in a map and calls x.SomeMethod()
}

When I try this, see https://go.dev/play/p/cJoH5YwEHaK , I get an error message for (1): "cannot use type V outside a type constraint: interface is (or embeds) comparable".  If I remove the line (1) I get an error for (2) instead: "invalid map key type val (missing comparable constraint)".

Is there a way to make something like this work?

Many thanks,
Jochen

Ian Lance Taylor

unread,
Feb 17, 2023, 6:47:09 PM2/17/23
to Jochen Voss, golang-nuts
Are you using Go 1.20? See https://go.dev/blog/comparable .

Ian

Jochen Voss

unread,
Feb 17, 2023, 6:55:34 PM2/17/23
to golang-nuts
Dear Ian,

Yes, I'm using 1.20.1.

I hadn't seen the blog post yet, will read this next.  Thanks for pointing me at this.  Judging from the first paragraph of the blog post alone, the change described there may not solve my problem, though.

All the best,
Jochen

Jochen Voss

unread,
Feb 17, 2023, 7:07:42 PM2/17/23
to golang-nuts
Thanks again, reading the blog post indeed solved the problem!

On Friday, 17 February 2023 at 23:47:09 UTC Ian Lance Taylor wrote:
Reply all
Reply to author
Forward
0 new messages