I'm trying to create a BST, add a node, and print the data in that node, but I keep getting invalid memory address or nil pointer dereference errors. I know something is wrong with my pointers, and I've been fiddling around with them all afternoon, and I can't seem to get it right. Could someone please take a look and let me know what stupid mistake I'm making?
package main
import "fmt"
type node struct {
data int
left *node
right *node
}
type root struct {
root *node
}
func (bt root) addNode(n *node, data int) {
if n == nil {
newNode := node{
data: data,
left: nil,
right: nil,
}
n = &newNode
fmt.Println("Works")
} else if data < n.data {
bt.addNode(n.left, data)
} else {
bt.addNode(n.right, data)
}
}
func main() {
tree := root{root: nil}
tree.addNode(tree.root, 6)
fmt.Println(tree.root.data)
}
n = &newNodeinaddNodeoverwrites the contents of the variablenwhich is an argument to the method and hence is a local variable in it. The result of this assignment is therefore not visible in the caller because the assignment had modified the copy of the caller's variable. Hencetree.rootremainsnil, which you could have easily seen if you have printed that value. To modify a pointer-typed variable in a function, you has to pass it a pointer to that pointer and derefence it when assigning—like in*ptrToPtr = someAddress.tree.addNode(tree.root)the contents of the variabletree.root, which isnil, is copied into the local variablenof theaddNodemethod, and then that method overwrites the content of that variable.