我實現了一個基于泛型的 Set,一切正常,直到我使用 struct 作為 Set 元素而不是基類型。我有一個編譯錯誤。去版本:go version go1.18 windows/amd64下面的代碼在功能上不符合要求AddSet。package mainimport ( "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)}運行時:> 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如果Key只有1個字段,則可以編譯成功。如果我使用for v := range another { s[v]=struct{}{} },它可以編譯成功。我覺得很奇怪,有人可以解釋一下嗎?
1 回答

阿波羅的戰車
TA貢獻1862條經驗 獲得超6個贊
看起來像這個編譯器錯誤。它在 Go 1.19 中得到修復并向后移植到 Go 1.18.2。
如果您使用的是舊版本,我建議maps您像您已經嘗試過的那樣,簡單地放棄軟件包并手動執行操作。這只是一個簡單的循環:
func (s Set[T]) AddSet(another Set[T]) {
for k := range another {
s[k] = struct{}{}
}
}
@icza 將命名映射類型顯式轉換為其基礎類型的注釋也有效:
maps.Copy(map[T]struct{}(s), another)
如果您使用需要多個映射類型參數(具有相同約束)的函數,如maps.Equalor maps.EqualFunc,您必須轉換兩個參數:
func (s Set[T]) Compare(another Set[T]) bool {
// signature is Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
return maps.Equal(map[T]struct{}(s), map[T]struct{}(another))
}
似乎用 len >= 2 的數組實例化的參數化映射類型也重現了崩潰。
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消