On Mon, Apr 22, 2024 at 9:54 PM Ian Lance Taylor <i...@golang.org> wrote:
>
> On Mon, Apr 22, 2024 at 2:25 PM Jochen Voss <jochen.v...@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/CAFC_Vt6-zxOO7hT9vg%2BTmm3A%2B4FSGu6ibCX6kXJ1A52DzwC1JA%40mail.gmail.com.

Reply via email to