据我了解,我无法在 Go 中为用户定义的类型定义相等性。那么计算某些自定义类型(可能是递归定义)的不同对象数量的惯用方法是什么。这是我正在尝试做的事情的一个例子。
package main
import "fmt"
type tree struct {
left *tree
right *tree
}
func shapeOf(a tree) string {
temp := "{"
if a.left != nil {
temp += shapeOf(*(a.left))
}
temp += "}{"
if a.right != nil {
temp += shapeOf(*(a.right))
}
temp += "}"
return temp;
}
func main() {
a := tree{nil, nil}
b := tree{nil, &a}
c := tree{nil, nil}
d := tree{nil, &c}
e := tree{nil, nil}
f := tree{&e, nil}
s := make(map[string]bool)
s[shapeOf(b)] = true
s[shapeOf(d)] = true
s[shapeOf(f)] = true
fmt.Println(len(s)) // As required, prints 2 because the first two trees have the same shape
}
它可以工作,但是字符串的使用非常难看,而且可能效率也很低。显然我可以很容易地编写一个递归方法来判断两棵树是否相等——比如
func areEqual(a, b tree) bool
但这不会让我使用树作为地图键。做这种事情的惯用 Go 方法是什么?
守着星空守着你
相关分类