Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go 1.8 Generic how to defined a new-able type parameter with interface

This used to work in go1.18beta1, but not works in go1.8rc1

package main

type A struct{}

func (*A) Hello() {
    println("Hello")
}

func Create[M any, PT interface {
    Hello()
    *M
}](n int) (out []*M) {
    for i := 0; i < n; i++ {
        v := PT(new(M))
        v.Hello()
        out = append(out, v)
    }
    return
}

func main() {
    println(Create[A](2))
}

Execute will throw

./prog.go:16:21: cannot use v (variable of type PT constrained by interface{Hello(); *M}) as type *M in argument to append:
    PT does not implement *M (type *M is pointer to interface, not interface)

Seems due to this limitation:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Embedding a type parameter, or a pointer to a type parameter, as an unnamed field in a struct type is not permitted. Similarly, embedding a type parameter in an interface type is not permitted. Whether these will ever be permitted is unclear at present.

How can I do this in go1.8rc1 ?

>Solution :

You have to convert v back to *M again.

out = append(out, (*M)(v))

I believe the error you got is about assignability. Both M and PT are different named type parameters and you can’t assign one to the other without explicit conversion.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading