Thank you both! This works, see my code below. Followup question: is there a way to refer to the new type without having to list both the element type and the pointer type separately? Below I have to write C[A, *A], which looks slightly ugly. And in my real application something like Creator OrderedArray[ProperName] would look much more readable than Creator OrderedArray[ProperName, *ProperName] .
Many thanks, Jochen type Type interface{} type Settable[E Type] interface { *E Set(int) } type C[E any, P Settable[E]] struct { Val []E } func (c *C[E, P]) Set(v int) { for i := range c.Val { var ptr P = &(c.Val[i]) ptr.Set(v) } } var c = C[A, *A]{Val: []A{1, 2, 3}} On Tuesday 23 April 2024 at 03:36:25 UTC+1 Nagaev Boris wrote: > On Mon, Apr 22, 2024 at 9:54 PM Ian Lance Taylor <ia...@golang.org> wrote: > > > > On Mon, Apr 22, 2024 at 2:25 PM Jochen Voss <joche...@gmail.com> wrote: > > > > > > Using generics, can I somehow write a constraint which says that *T > (instead of T) implements a certain interface? The following code > illustrated what I'm trying to do: > > > > > > type A int > > > > > > func (a *A) Set(x int) { > > > *a = A(x) > > > } > > > > > > type B string > > > > > > func (b *B) Set(x int) { > > > *b = B(strconv.Itoa(x)) > > > } > > > > > > type C1 struct { > > > Val []A > > > } > > > > > > func (c *C1) Set(v int) { > > > for i := range c.Val { > > > c.Val[i].Set(v) > > > } > > > } > > > > > > type C2 struct { > > > Val []B > > > } > > > > > > func (c *C2) Set(v int) { > > > for i := range c.Val { > > > c.Val[i].Set(v) > > > } > > > } > > > > > > I would like to use generics to use a single definition for the > methods which here are func (c *C1) Set(v int) and func (c *C2) Set(v int). > (My real code has many base types, instead of just A and B.) How can I do > this? > > > > > > I tried the naive approach: > > > > > > type C[T interface{ Set(int) }] struct { > > > Val []T > > > } > > > > > > but when I try to use the type C[A] now, I get the error message "A > does not satisfy interface{Set(int)} (method Set has pointer receiver)". > > > > > > type C[P interface { > > *E > > Set(int) > > }, E any] struct { > > Val []P > > } > > > > Ian > > > > I think it should be this (s/Val []P/Val []E/): > > type C[P interface { > *E > Set(int) > }, E any] struct { > Val []E > } > > > > -- > Best regards, > Boris Nagaev > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c5571d6c-d4d1-4cb9-9617-d5405f68d66an%40googlegroups.com.