我实现了一个基于泛型的 Set,一切正常,直到我使用 struct 作为 Set 元素而不是基类型。我有一个编译错误。
去版本:go version go1.18 windows/amd64
下面的代码在功能上不符合要求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)
}
运行时:
> 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{}{} },它可以编译成功。
我觉得很奇怪,有人可以解释一下吗?
回首忆惘然
阿波罗的战车
随时随地看视频慕课网APP
相关分类