tree.Print: "Hash of unhashable type main.Node" error
Closed this issue · 2 comments
godstanis commented
Hi, I try to print my simple tree but I get the mentioned error, here is my code:
package main
import (
"fmt"
"github.com/shivamMg/ppds/tree"
)
type Node struct {
data string
depth int
c []*Node
}
func (n Node) Data() interface{} {
return n.data
}
func (n Node) Children() (children []tree.Node) {
for _, c := range n.c {
children = append(children, tree.Node(c))
}
return
}
func main() {
parent := Node{"Test", 0, nil}
buildBinaryTreeFromNode(&parent, 3, 0)
fmt.Println(parent)
tree.Print(parent)
}
func buildBinaryTreeFromNode(node *Node, maxDepth int, curDepth int) {
if curDepth >= maxDepth {
return
}
curDepth++
if node.c == nil {
node.c = []*Node{{"Element", curDepth, nil}, {"Element", curDepth, nil}}
}
for idx, _ := range []int{0, 1} {
buildBinaryTreeFromNode(node.c[idx], maxDepth, curDepth)
}
}
shivamMg commented
Slices in go are unhashable. So if you've a struct with one of the fields as a slice it will also be unhashable. See: https://play.golang.org/p/u2xb1fxVt3d
The library counts on your Node type to be hashable. I will suggest using pointer to Node everywhere - which will make it hashable.
Here's your snippet where I've made Data()
and Children()
receivers to be pointer to Node: https://play.golang.org/p/3Q3KKzaLliU
package main
import (
"fmt"
"github.com/shivamMg/ppds/tree"
)
type Node struct {
data string
depth int
c []*Node
}
func (n *Node) Data() interface{} {
return n.data
}
func (n *Node) Children() (children []tree.Node) {
for _, c := range n.c {
children = append(children, tree.Node(c))
}
return
}
func main() {
parent := Node{"Test", 0, nil}
buildBinaryTreeFromNode(&parent, 3, 0)
fmt.Println(parent)
tree.Print(&parent)
}
func buildBinaryTreeFromNode(node *Node, maxDepth int, curDepth int) {
if curDepth >= maxDepth {
return
}
curDepth++
if node.c == nil {
node.c = []*Node{{"Element", curDepth, nil}, {"Element", curDepth, nil}}
}
for idx, _ := range []int{0, 1} {
buildBinaryTreeFromNode(node.c[idx], maxDepth, curDepth)
}
}
Hope this helps.
godstanis commented
Yeah, right. Ok, thanks)