You can do this with type-list interfaces:
https://go2goplay.golang.org/p/wfHnVHOMcyK

This is one of the harder parts of the proposal to understand IMHO, but
perhaps it will become easier with familiarity.

On Tue, 5 Jan 2021, 17:32 Brian Candler, <b.cand...@pobox.com> wrote:

> Question: how to make a generic function which takes a type T where the
> constraint is "*T satisfies a given interface"?
>
> func (m *MyMap[KT, VT]) init() {
>         m.data = make(map[KT]VT)
> }
>
> type Initializer interface {
> init()
> }
>
> func mynew[T Initializer]() *T {
> t := new(T)
> t.init()
> return t
> }
>
> /* or:
> func mynew[T Initializer]() *T {
> var t T
> t.init()
> return &t
> }
> */
>
> func main() {
> m := mynew[MyMap[string, int]]()
> }
>
> gives:
>
> type checking failed for main prog.go2:34:13: MyMap[string, int] does not
> satisfy Initializer: wrong method signature
>         got func (*MyMap[KT, VT]).init()
>         want func (Initializer).init()
>
> Full code: https://go2goplay.golang.org/p/INcenfcInSl
>
>
> --
> 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/13dcb9b5-da98-49b9-abf7-05c95b1d4ebdn%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/13dcb9b5-da98-49b9-abf7-05c95b1d4ebdn%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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/CAJhgacgvJ%3D6eoH_Uh%2B69SdDk3C0nMep35SUhpv4QnsgAQw3kcA%40mail.gmail.com.

Reply via email to