Another generics question

88 views
Skip to first unread message

Jochen Voss

unread,
Feb 17, 2023, 7:46:59 PM2/17/23
to golang-nuts
Hello,

I would like to write a  type constraint which matches types like the following:

type v1 int

func (obj v1) Add(other v1) v1 {
    return obj + other
}

type v2 string

func (obj v2) Add(other v2) v2 {
    return obj + other
}

This should match anything with an Add() method which can add another item of the same type.  I want to be able to write a function like the following:

func Double[Adder ...???...](x Adder) Adder {
    return x.Add(x)
}

My best attempts is https://go.dev/play/p/R0WLqSq9dys , but this doesn't quite work.  What is the correct type constraint to use?

Many thanks,
Jochen

Ian Lance Taylor

unread,
Feb 17, 2023, 8:31:16 PM2/17/23
to Jochen Voss, golang-nuts
On Fri, Feb 17, 2023 at 4:47 PM Jochen Voss <joche...@gmail.com> wrote:,
This is one way to do it: https://go.dev/play/p/uUxkvds5HLB .

Ian

Jochen Voss

unread,
Feb 18, 2023, 3:20:17 AM2/18/23
to golang-nuts
Thanks a lot!

As an aside, the playgound is great.  It made this conversation so much easier!

All the best,
Jochen
Reply all
Reply to author
Forward
0 new messages