我正在尝试为 Go 程序编写一个类型约束,它接受“任何你可以接受 len() 的东西”。但我真的无法弄清楚。
我想要这样的东西:
LenOf[m Measurable](m M) int {
return len(m)
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一些事情。外汇。这个天真的东西可以编译,但不适用于所有类型(例如 fx []User):
type Measurable interface {
~string | []any | ~map[any]any
}
Run Code Online (Sandbox Code Playgroud)
然后继续类似下面的内容,这不仅使函数签名LenOf()极其笨拙,而且在调用站点上编写起来也很笨拙(并且仍然无法编译)
type Measurable[K comparable, V any] interface {
~string | []V | ~map[K]V
}
Run Code Online (Sandbox Code Playgroud)