Go 1.18 generic compile error when use maps.Copy on map with struct key

I implemented a Set based on generic, and everything ok until i use struct as Set element instead of base type. I got an compliation error.

go version: go version go1.18 windows/amd64

Below code is failed to complie in function AddSet.

package main

import (
	"fmt"

	"golang.org/x/exp/maps"
)

type Key struct {
	A, B int
}

func main() {
	s := SetOf(
		Key{1, 1},
		Key{2, 2},
		Key{3, 3},
	)
	s.AddSet(SetOf(
		Key{3, 3},
		Key{4, 4},
		Key{5, 5},
	))

	fmt.Println(s)
}

type Set[T comparable] map[T]struct{}

func SetOf[T comparable](vs ...T) Set[T] {
	s := Set[T]{}
	for _, v := range vs {
		s[v] = struct{}{}
	}
	return s
}

func (s Set[T]) AddSet(another Set[T]) {
	maps.Copy(s, another)
}

when run it:

> go run .\main.go
# command-line-arguments
.\main.go:19:10: cannot use &.autotmp_29 (type *struct { A int; B int }) as type *Key in argument to runtime.mapassign
<autogenerated>:1: cannot use &.autotmp_12 (type *struct { A int; B int }) as type *Key in argument to runtime.mapassign
  • if Key only has 1 field, it can be compiled successful.
  • if i use for v := range another { s[v]=struct{}{} }, it can be compiled successful.

i think it’s strange, can someone explain please? i also post a stackoverflow question: go 1.18 generic compile error when use maps.Copy on map with struct key - Stack Overflow

blackgreen has given an great answer to this, see the link to Stackoverflow question.

but i don’t know if any way to close this topic mannully.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.