A
A
Artem Rogozin2019-09-01 21:15:36
go
Artem Rogozin, 2019-09-01 21:15:36

Why doesn't a pointer change another pointer in golang?

func (t *Tree) Delete(value int) bool {

  if t.Search(value) {
    currentNode := t.root

    for currentNode != nil {
      if value == currentNode.value {
        if currentNode.left == nil && currentNode.right == nil {
          currentNode = nil
          return true
        }
      } else if value < currentNode.value {
        currentNode = currentNode.left
      } else {
        currentNode = currentNode.right
      }
    }
  }

  return false
}

There is such a function for deleting an element in a binary tree (it is unfinished and deletes an element only if the element being deleted has no descendants). Consider the case when we have only root in the tree: In the currentNode function, in this case, it will point to root, but when currentNode = nil is assigned, root does not change. Why is this happening?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-09-01
@pav5000

currentNode is a variable that exists only in this function. It's a pointer, you assign a value to it, and then you assign nil to it. From this, the previously assigned object will not change, because you are only changing the pointer to this object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question